0

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>
Nitin
  • 3
  • 1
  • 2
  • 1
    possible duplicate of https://stackoverflow.com/questions/9683054/xpath-to-select-element-based-on-childs-child-value ? – Ralph Thomas Hopper Oct 03 '17 at 16:46
  • 3
    Possible duplicate of [How can i get the parent of node text value in c#?](https://stackoverflow.com/questions/10580607/how-can-i-get-the-parent-of-node-text-value-in-c) – Aleks Andreev Oct 03 '17 at 16:51
  • My question appears to be different from both the comments above. I am looking for "TransactionID" and it is in different parent nodes, – Nitin Oct 03 '17 at 17:28

1 Answers1

0

Using Linq2Xml and XPath

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();
Eser
  • 12,346
  • 1
  • 22
  • 32