How to use XPath on TXMLDocument which has namespace prefixes?

前端 未结 5 2018
猫巷女王i
猫巷女王i 2021-01-03 07:35

I have an XML packet received from a third-party web server:




        
5条回答
  •  鱼传尺愫
    2021-01-03 07:44

    One solution could be to remove all namespaces before you start processing your XML:

    class function TXMLHelper.RemoveNameSpaces(XMLString: String): String;
    const
      // An XSLT script for removing the namespaces from any document.
      // From http://wiki.tei-c.org/index.php/Remove-Namespaces.xsl
      cRemoveNSTransform =
        '' +
        '' +
    
        '' +
        '    ' +
        '      ' +
        '    ' +
        '' +
    
        '' +
        '    ' +
        '      ' +
        '    ' +
        '' +
    
        '' +
        '    ' +
        '      ' +
        '    ' +
        '' +
    
        '';
    
    var
      Doc, XSL, Res: IXMLDocument;
      UTF8: UTF8String;
    begin
       try
         Doc := LoadXMLData(XMLString);
         XSL := LoadXMLData(cRemoveNSTransform);
         Res := NewXMLDocument;
         Doc.Node.TransformNode(XSL.Node,Res);  // Param types IXMLNode, IXMLDocument
         Res.SaveToXML(Utf8);      // This ensures that the encoding remains utf-8
         Result := String(UTF8);
       except
         on E:Exception do Result := E.Message;
       end;
    end; { RemoveNameSpaces }
    

    (TXMLHelper is a helper class that I have with some useful XML handling functions)

提交回复
热议问题