I have an xml message as shown below. When I am processing this xml I want to get all parent nodes of "TransactionID" node that contain TransactionID with value of TRN001. I am using C# to do this. How can this be done ?
TIA
<Parent xmlns="http://baqwas">
<Child1>
<Child1>
<TransactionID>TRN001</TransactionID>
</Child1>
<Child1>
<TransactionID>TRN002</TransactionID>
</Child1>
</Child1>
<Child2>
<Child2>
<TransactionID>TRN001</TransactionID>
<TransDetails>123</TransDetails>
</Child2>
<Child2>
<TransactionID>TRN001</TransactionID>
<TransDetails>456</TransDetails>
</Child2>
<Child2>
<TransactionID>TRN001</TransactionID>
<TransDetails>789</TransDetails>
</Child2>
<Child2>
<TransactionID>TRN001</TransactionID>
<TransDetails>101112</TransDetails>
</Child2>
<Child2>
<TransactionID>TRN002</TransactionID>
<TransDetails>ABC</TransDetails>
</Child2>
<Child2>
<TransactionID>TRN002</TransactionID>
<TransDetails>DEF</TransDetails>
</Child2>
<Child2>
<TransactionID>TRN002</TransactionID>
<TransDetails>GHI</TransDetails>
</Child2>
</Child2>
</Parent>
var xDoc = XDocument.Parse(yourxmlstring);
XmlNamespaceManager mgr = new XmlNamespaceManager(xDoc.CreateNavigator().NameTable);
mgr.AddNamespace("ns", "http://baqwas");
var elems = xDoc.XPathSelectElements("//ns:TransactionID[text()='TRN001']", mgr)
.Select(x=>x.Parent)
.ToList();
or
var elems = xDoc.XPathSelectElements("//*/ns:TransactionID[text()='TRN001']", mgr)
.ToList();
or
XNamespace ns = "http://baqwas";
var elems = xDoc.Descendants(ns + "TransactionID")
.Where(x => (string)x == "TRN001")
.Select(x => x.Parent)
.ToList();
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.