2013-02-27 77 views
2

下面是XML文件的内容:使用simpleXML解析嵌套命名空间的XML?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<w:document xmlns:ve="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:w10="urn:schemas-microsoft-com:office:word" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml"> 
    <w:body> 
     <w:p w:rsidR="00546015" w:rsidRDefault="00546015"> 
      <w:r> 
       <w:t xml:space="preserve">Hello </w:t> 
      </w:r> 
      <w:proofErr w:type="spellStart"/> 
      <w:r> 
       <w:t>Doctor</w:t> 
      </w:r> 
      <w:proofErr w:type="spellEnd"/> 
      <w:r> 
       <w:t>,</w:t> 
      </w:r> 
     </w:p> 
     <w:p w:rsidR="00546015" w:rsidRDefault="00546015" w:rsidP="00B72192"> 
      <w:r> 
       <w:t xml:space="preserve">I hope you are doing well. Thanks for taking the time to speak with us on Skype yesterday. It is always a pleasure talking with you. </w:t> 
      </w:r> 
     </w:p> 
     <w:p w:rsidR="00546015" w:rsidRDefault="00546015"/> 
     . 
     . 
     . 
     . 
     . 
     and this list goes on 

这里是我开始了代码,但我不知道它是否是我下面还是有一些更好的方式来实现这一目标的正确的方法?

// load the xml into the object 
$xml = simplexml_load_file('word/document.xml'); 

//Use that namespace 
$namespaces = $xml->getNameSpaces(true); 

//Now we don't have the URL hard-coded 
$w_doc = $xml->children($namespaces['w']); 
$document = $w_doc->document; 

$w_body = $document->document->children($namespaces['w']); 

$body = $w_body->body; 

如何通过元素循环以获取<w:t>的内容?

回答

4

Xpath的将可能是最简单的:

// load the xml into the object 
$xml = simplexml_load_file('word/document.xml'); 

//Use that namespace 
$namespaces = $xml->getNameSpaces(true); 

$xml->registerXPathNamespace('w', $namespaces['w']); 

$nodes = $xml->xpath('/w:document/w:body//w:t'); 

foreach($nodes as $node) { 
    echo (string) $node . "\n\n"; 
} 
+0

能否请您进一步阐述,如何让有文本的每个节点的位置或路径,以及我们将如何修改任何特定节点的文本? – atif 2013-02-27 10:25:45

+0

@atif:这超出了你的初始问题的范围,并且还需要额外的信息,例如为什么你需要节点的完整路径以及它将用于什么,以及修改节点的意图是什么 - 即。是否适合内存使用,你是否要将文件写回磁盘等。请发布一个新的问题,并附上任何相关的代码。 – prodigitalson 2013-02-27 13:58:16