简体   繁体   中英

SelectSingleNode statement with a variable node

I have two XML files types with different schemas

First schema:

<Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pain.001.001.03\">
    <CstmrCdtTrfInitn>
       <PmtInf>
          <DbtrAcct>
              <Id>11111111111111111</Id>
          </DbtrAcct>
       </PmtInf>
    </CstmrCdtTrfInitn>
</Document>

Second schema:

<Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pain.001.001.02\">
   <CstmrCdtTrfInitn>
      <PmtInf>
          <DbtrAcct>
               <Id>11111111111111111</Id>
          </DbtrAcct>
      </PmtInf>
   </CstmrCdtTrfInitn>
</Document>

I tried the following code in order to get the value of the node id in both type of schemas, all files xml exist in the same folder, I did a loop to read all xml files, the code below didn't work any idea please ?

string xmlText = File.ReadAllText(file).Replace("<Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pain.001.001.03\">", "").Replace("<Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pain.001.001.02\">", "").Replace("</Document>", "").Replace("<CstmrCdtTrfInitn>", "").Replace("</CstmrCdtTrfInitn>", "").Replace("<pain.001.001.02>", "").Replace("</pain.001.001.02>", "");
var doc = new XmlDocument();
doc.LoadXml(xmlText);
string id= doc.SelectSingleNode("./PmtInf/DbtrAcct/Id")["id"].InnerText; ;
MessageBox.Show(id);

You don't need those string operations. Using Linq to Xml

var id = (string)XDocument.Load(filename)
                          .Descendants()
                          .FirstOrDefault(d => d.Name.LocalName == "Id");

You can use XPath too

var id = (string)XDocument.Load(filename).XPathSelectElement("//*[local-name()='Id']");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM