duangaixing1509
2016-06-24 21:31
浏览 60

使用命名空间读取XML文件

I need som help reading a XML that has namespaces. I can read file with out any namepaces but not with namespaces..

XML sample:

<?xml version="1.0" encoding="utf-8"?>
<OrderResponse xmlns:cac="urn:basic:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:xsi="http://www.w3.org/" xmlns:cbc="urn:basic:names:specification:ubl:schema:xsd:BasicComponents-2" xmlns="urn:basic:names:specification:ubl:schema:xsd:OrderResponse-2">
  <cbc:UBLVersionID>2.1</cbc:UBLVersionID>
  <cbc:AccountingCostCode>TESTER TEST</cbc:AccountingCostCode>
  <cac:OrderReference>
    <cbc:ID>100067010</cbc:ID>
    <cbc:IssueDate>2016-06-15</cbc:IssueDate>
    <cbc:OrderTypeCode>EDI</cbc:OrderTypeCode>
  </cac:OrderReference>
</OrderResponse>

I need to get the value of the .. Im trying do it with DomDocument. Here is my code:

function SearchXMLID($xml){
var_dump($xml);
$doc = new DOMDocument();
$doc->load($xml);
$id = $doc->getElementsByTagNameNS('urn:basic:names:specification:ubl:schema:xsd:CommonAggregateComponents-2','cbc:ID');

  foreach($id as $i){
    echo "<pre>";var_dump('NS',$i->nodeValue,PHP_EOL);"</pre>";

  }
}

$files = glob('dataXMl/*xml');
echo "<pre>";var_dump($files,PHP_EOL);"</pre>";

foreach($files as $f){
    SearchXMLID($f);
 }

This code works but is getting all namespaces with 'cbc:' and stores the in a string..

    array(1) {
  [0]=>
  string(17) "dataXMl/test1.xml"
}
string(1) "
"
string(17) "dataXMl/test1.xml"
string(2) "NS"
string(40) "
    100000050
    2016-06-15
    EDI
  "
string(1) "
"

It gets all tags with the namespace 'cbc'.. but i want to get the tag 'cbc:ID' only.

What am i doing wrong?

</div>
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyan8070 2016-06-24 22:39
    已采纳

    I'm no expert with php coding but my gut tells me that both of your parameters for getElementsByTagNameNS are wrong.

    Try this:

    $id = $doc->getElementsByTagNameNS('urn:basic:names:specification:ubl:schema:xsd:BasicComponents-2','ID');
    

    i.e.

    use the correct namespace-uri: "urn:basic:names:specification:ubl:schema:xsd:BasicComponents-2" and drop the cbc prefix
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题