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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码