2012-05-15 32 views
0

我試圖使用XPath打印複雜的XML節點值,我附加了幫助查看我需要達到的路徑(紅色下劃線)的圖像。 XML image 原始XML文件可以發現here在PHP中使用XPath打印XML節點

我是想這樣的事情:

<?php 
$xml = simplexml_load_file('document.xml'); 

    echo "<strong>Using direct method...</strong><br />"; 
    $names = $xml->xpath('/w:document/w:body/w:tbl[0]/w:tr[1]/w:tc[0]/w:p/w:r/w:t'); 
    foreach($names as $name) { 
     echo "Found $name<br />"; 
    } 

?> 

這種方法,我用替換此節點:

$file = "document.xml";           
    $fp = fopen($file, "rb") or die("error"); 
    $str = fread($fp, filesize($file)); 
    $xml = new DOMDocument();         
    $xml->formatOutput = true; 
    $xml->preserveWhiteSpace = false; 
    $xml->loadXML($str) or die("Error"); 

    $root = $xml->documentElement; 
    $fnode = $root->childNodes->item(0); 

    $ori = $fnode->childNodes->item(1);      
    $ori1 = $ori->childNodes->item(3); 
    $ori2 = $ori1->childNodes->item(1); 
    $ori3 = $ori2->childNodes->item(1); 
    $ori4 = $ori3->childNodes->item(1); 
    $ori5 = $ori4->childNodes->item(1); 
     $wt  = $xml->createElement("w:t"); 
    $wtText = $xml->createTextNode("".$name." ".$item.""); 
    $wt->appendChild($wtText); 
     $ori4->replaceChild($wt,$ori5); 
     $xml->save("document.xml"); 
+0

編輯我的帖子,我可以使用PHPDOM訪問該節點並替換該節點,但我不知道如何只讀取這一個XML節點 –

回答

1
<?php 

// Load XML 
$doc = new DOMDocument(); 
$doc->load("document.xml"); 

// Use xpath to grab the node in question. I copied your xpath 
// query as-is, assuming it was capable of targetting exactly 
// the node you are trying to replace. If it returns more than 
// one node, then only the first will be replaced. 
// If this isn't what you want, I suggest modifying your xpath 
// query to match exactly the single node you want to replace. 
$xpath = new DOMXPath($doc); 
$oldElement = $xpath->query("/w:document/w:body/w:tbl[0]/w:tr[1]/w:tc[0]/w:p/w:r/w:t")->item(0); 
$newElement = $doc->createElementNS("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "w:t", $name . " " . $item); 

// Replace old element with new element 
$oldElement->parentNode->replaceChild($newElement, $oldElement); 

?> 
相關問題