首页 > 解决方案 > 如何使用命名空间读取 XML

问题描述

我想在这个字符串 XML 中获取元素 TransactionCode,但我的代码不起作用。

这是字符串 XML:

string xml1="<PayBillsByCustomerCodeResponse xmlns='http://tempuri.org/' xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'><PayBillsByCustomerCodeResult><xs:schema id='NewDataSet' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns='' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>xs:element name='NewDataSet' msdata:IsDataSet='true' msdata:MainDataTable='table' msdata:UseCurrentLocale='true'><xs:complexType><xs:choice minOccurs='0' maxOccurs='unbounded'><xs:element name='table'><xs:complexType><xs:sequence><xs:element name='TransactionCode' type='xs:string' minOccurs='0'></xs:element><xs:element name='Status' type='xs:string' minOccurs='0'></xs:element></xs:sequence></xs:complexType></xs:element></xs:choice></xs:complexType></xs:element></xs:schema><diffgr:diffgram xmlns:diffgr='urn:schemas-microsoft-com:xml-diffgram-v1' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'><DocumentElement xmlns=''><table diffgr:id='table1' msdata:rowOrder='0' diffgr:hasChanges='inserted'><TransactionCode>IN820874120133045554</TransactionCode><Status>0</Status></table><table diffgr:id='table2' msdata:rowOrder='1' diffgr:hasChanges='inserted'><TransactionCode>IN738800517433045554</TransactionCode><Status>0</Status></table></DocumentElement></diffgr:diffgram></PayBillsByCustomerCodeResult></PayBillsByCustomerCodeResponse>";


XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xml1);
        var ns = new XmlNamespaceManager(new NameTable());
        //ns.AddNamespace("i", "http://www.w3.org/2001/XMLSchema-instance");
        ns.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
        ns.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
        ns.AddNamespace("t", "'http://tempuri.org/");
        string xpath = "t:PayBillsByCustomerCodeResponse/t:PayBillsByCustomerCodeResult/t:diffgr/t:DocumentElement/t:table";
       // string xpath1 = "response/billinf/xml-fragment/a:Bills/a:BillInfo";
        var nodes = xmlDoc.SelectNodes(xpath, ns);
       foreach (XmlNode childrenNode in nodes)
{
    string s = childrenNode.SelectSingleNode("TransactionCode", ns).InnerText;
      Console.Write(s);
     Console.Write("\n");

标签: c#asp.netxmlxmldocument

解决方案


推荐阅读