Reputation: 5241
I am receiving 'chunks' of xml over an http response stream. Each chunk is a complete mini xml hierarchy, such as:
<chunk1>
<id>1</id>
<data>blah blah-blah</data>
</chunk1>
...
(30 seconds later)
...
<chunk2>
<id>2</id>
<data>blah blah-blah</data>
</chunk2>
...
(30 seconds later)
...
<chunk1>
<id>3</id>
<data>blah blah-blah</data>
</chunk1>
What is the best way in c# to read each 'chunk' into an XElement for further processing? Each chunk may have a different root element.
I have seen responses to similar questions. However, the responses did not seem optimal, as they involved processing each node. I just want to read the stream until I reach the closing node corresponding to the opening chunk node, feed the whole chunk into an XElement, call a method to process it, and then wait for the next chunk.
Upvotes: 2
Views: 800
Reputation: 5241
This does what I was looking for:
XmlReader reader = XmlReader.Create(stream, new XmlReaderSettings() { ConformanceLevel = ConformanceLevel.Fragment });
while (reader.Read())
{
using (XmlReader subTreeReader = reader.ReadSubtree())
{
XElement xmlData = XElement.Load(subTreeReader);
Process(xmlData);
}
}
Upvotes: 2