Link to home
Start Free TrialLog in
Avatar of ethar turky
ethar turkyFlag for Saudi Arabia

asked on

XML MSXML2.DOMDocument30 selectNodes

Dear all,
I have following xml document:

<Site some_attributes="xxx">
    <Page id="1"></Page>
    <page id="2"></page>
    <Style></Style>
</Site>

Open in new window

Need to use following C# code to select Site node[only] with its all attributes + Page id=2 [with its all child nodes].

MSXML2.DOMDocument30 XMLSourceDataSingleDoc = new MSXML2.DOMDocument30();                                   
XMLSourceDataSingleDoc.loadXML(XMLSiteSourceData.xml );
XMLSourceDataSingleDoc.selectNodes("xxxxxxxxxxx");

Open in new window

Avatar of Karrtik Iyer
Karrtik Iyer
Flag of India image

You will have to give XPATH correctly, I haven't tried using MSXML but it should be something like below.
/Site[Page[@id = 1]]. // node that you want to select and the filters within that node.
I tried using C# XMLDocument and SelectSingle node methods and it looks like below.
            XmlDocument doc = new XmlDocument();
            doc.Load(@"E:\Test.xml");
            XmlNode root = doc.DocumentElement;
            // Add the namespace.
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
            nsmgr.AddNamespace("st", "urn:sites-schema");
            XmlNode node = root.SelectSingleNode(
    "descendant::st:Site[st:Page[@id='1']]", nsmgr);
            Console.WriteLine(node.InnerXml);

Open in new window

XML looks like below:
<?xml version='1.0'?>
<sites xmlns="urn:sites-schema">
  <Site some_attributes="xxx">
    <Page id="1"></Page>
    <Page id="2"></Page>
    <Style></Style>
  </Site>
</sites>

Open in new window


You look at below reference for more help:
https://msdn.microsoft.com/en-us/library/cc189056%28v=vs.95%29.aspx
http://www.csharp-examples.net/xml-nodes-by-attribute-value/
Avatar of ethar turky

ASKER

Thanks for your reply,
the output I need is :
<Site some_attributes="xxx">
    <page id="1"></page>
</Site>

Open in new window

You can use the below XPath:
   XmlNode node = root.SelectSingleNode(
    "descendant::st:Site/st:Page[@id='2']", nsmgr);
And get the outerXML
node.OuterXml
which shall give you
<Page id="2"></Page>
Then you may have to append the parent node's XML to get the desired value.
I shall check further if there is any other direct way to just the output that you desire (as per your last comment)
ASKER CERTIFIED SOLUTION
Avatar of Karrtik Iyer
Karrtik Iyer
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for your great efforts...
You are welcome!