Reputation: 17
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);
Upvotes: 1
Views: 199
Reputation: 116138
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']");
Upvotes: 3