如何使用selectNodes在下面的XML中选择节点?

时间:2013-08-09 11:02:33

标签: xml dom

如何选择节点“nfeStatusServicoNF2Result”? 我尝试使用下面的代码,但selectNodes的结果为零。

代码示例

lXMLDoc := CoDOMDocument50.Create;
try
  lXMLDoc.loadXML(lRespose.DataString);

  lXMLDoc.setProperty('SelectionNamespaces', 'xmlns:n="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2"');

  lXmlNodes := lXMLDoc.selectNodes('n:nfeStatusServicoNF2Result');
  if lXmlNodes.length = 0 then
  begin
    lHostError := '';

    lXmlNodes := lXMLDoc.getElementsByTagName('n:Value');
    if lXmlNodes.length > 0 then
      lHostError := lHostError + lXmlNodes.item[0].text;

    lXmlNodes := lXMLDoc.getElementsByTagName('n:Text');
    if lXmlNodes.length > 0 then
      lHostError := lHostError + lXmlNodes.item[0].text;

    if lHostError = '' then
      lHostError := lRespose.DataString;

    raise Exception.Create(lHostError);
  end else
  begin
    Result := RemoveVersaoXML(lXmlNodes.item[0].text);
  end;
finally
  lXMLDoc := nil;
end;

Xml文件

<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
  <soap:Header>
    <nfeCabecMsg xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
      <cUF>31</cUF>
      <versaoDados>2.00</versaoDados>
    </nfeCabecMsg>
  </soap:Header>
  <soap:Body>
    <nfeStatusServicoNF2Result xmlns="http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2">
      <retConsStatServ xmlns="http://www.portalfiscal.inf.br/nfe" versao="2.00">
        <tpAmb>2</tpAmb>
        <verAplic>13_0_96</verAplic>
        <cStat>517</cStat>
        <xMotivo>Rejeicao: Falha no schema XML - inexiste atributo versao na tag raiz da     mensagem</xMotivo>
        <cUF>31</cUF>
        <dhRecbto>2013-08-08T17:45:48</dhRecbto>
      </retConsStatServ>
    </nfeStatusServicoNF2Result>
  </soap:Body>
</soap:Envelope>

2 个答案:

答案 0 :(得分:1)

请参阅此文章,了解如何向查询添加命名空间解析程序:

https://developer.mozilla.org/es/docs/Introduction_to_using_XPath_in_JavaScript

答案 1 :(得分:1)

通常,您必须先声明名称空间前缀,然后才能在XPath中使用它们。

在MSXML中,这可以通过设置SelectionNamespaces property完成,如下所示:

var
    lXMLDoc   : IXMLDOMDocument3;
begin
  ...
  lXMLDoc.setProperty('SelectionNamespaces', "xmlns:n='http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico2'");
  lXMLDoc.selectNodes('//n:nfeStatusServicoNF2Result');
  ...
end;

请注意,您可以选择任何您喜欢的前缀,但必须选择前缀。