tags:

views:

56

answers:

2

I want to extract a chunk of XML from a larger XML document. For example, my XML document looks like this

    <?xml version="1.0" encoding="utf-8"?>
<Root>
<CONTAINER>
    <FIRSTNODE>
        <CHILDNODE>
        </CHILDNODE>
    </FIRSTNODE>
</CONTAINER>
</Root>

If I wish to extract any portion. For example, I wish to extract everything contained within including attribute tags and values, how should I do this in C#?

I tried using this code, but it doesn't seem to be doing the trick.

     XmlDocument xdoc = new XmlDocument();
    xdoc.LoadXml(inputXML);
    Console.WriteLine(inputXML);
    string strOut = "";

    XmlNode node = xdoc.DocumentElement.ParentNode;
    XmlNodeList nodeList = node.ChildNodes;
    for (int n = 0; n < nodeList.Count; n++)
    {
        Console.WriteLine(nodeList[n].Name);
        if (nodeList[n].Name == "FIRSTNODE")
        {
            strOut = nodeList[n].OuterXml.ToString();
            Console.WriteLine(strOut.Length.ToString());
            return strOut;
        }
    }
+1  A: 
XEelement root = xml document;
XElement first = root.Element("Root").Element("Container").Element("FirstNode");

Something along that line, you might have to adjust the Element calls.

Femaref
+1  A: 

Have you tried with SelectSingleNode?

XmlNode n = xdoc.SelectSingleNode("//FIRSTNODE");    
Console.WriteLine(n.OuterXml);

Have a look for XPath

Hope this helps ...

PS: Sorry but I'm new here and don't know the editor ...

Tobias Pirzer