Distwo
Distwo

Reputation: 11749

Extract part of a big XML

I have to extract a part of an XML. My XML file can contain thousands of nodes and I would like to get only a part of it and have this part as an xml string.

My XML structure:

<ResponseMessage xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <ErrorResponse>
        <Code>SUCCESS</Code>
        <Message>Success</Message>
    </ErrorResponse>
    <OutputXml>
        <Response>
            <Product>
                <child1>xxx</child1>
                <child2>xxx</child2>
                ...
            </Product>
            <Product>
                <child1>xxx</child1>
                <child2>xxx</child2>
                ...
            </Product>
            ...
        </Response>
    </OutputXML>
</ResponseMessage>

I'm getting the XML from a webservice like that:

...
System.Net.WebResponse wResponse = req.GetResponse();
reqstream = wResponse.GetResponseStream();
System.IO.StreamReader reader = new System.IO.StreamReader(reqstream);

System.Xml.Linq.XDocument xmlResponse = System.Xml.Linq.XDocument.Parse(reader.ReadToEnd());

Then I tried to put the XML in a generic collection to process it using linq:

int startIndex = 0;
int nbItem = 25;
System.Text.StringBuilder outputXml = new System.Text.StringBuilder();
System.Collections.Generic.IEnumerable<System.Xml.Linq.XElement> partialList =
   xmlResponse.Elements("Response").Skip(startIndex).Take(nbItem);

foreach (System.Xml.Linq.XElement x in partialList)
{
    outputXml.Append(x.ToString());
}

My problem is that my list is always empty.

Upvotes: 0

Views: 679

Answers (2)

Caleb Keith
Caleb Keith

Reputation: 816

You can use an LINQ To Xml by using the following code:

IEnumerable<XElement> elements = xmlResponse.Root.Element("OutputXml").Element("Response").Elements("Product");

foreach(XElement element in elements)
{
    // Do Work Here
}

This will filter the list down to just products and it will select them correctly without using an index. Using indexes with xml is not the greatest idea because the xml can change.

Upvotes: 1

Victor Zakharov
Victor Zakharov

Reputation: 26424

You can use XPathEvaluate to read a subtree.

If your list is empty, chances are it is namespace problem, so you did not account for this namespace in your code xmlns:i="http://www.w3.org/2001/XMLSchema-instance". XDocument/XElement cannot resolve namespaces automatically.

See this topic on how to use namespaces with LINQ-to-XML.

Upvotes: 0

Related Questions