c# - XML Error: There are multiple root elements -
i getting xml web service. here xml looks like:
<parent> <child> text </child> </parent> <parent> <child> <grandchild> text </grandchild> <grandchild> text </grandchild> </child> <child> text </child> </parent> etc.
and here c# code:
stringbuilder output = new stringbuilder(); // create xmlreader using (xmlreader reader = xmlreader.create(new stringreader(xoresponse.@return))) { xmlwritersettings ws = new xmlwritersettings(); //ws.indent = true; using (xmlwriter writer = xmlwriter.create(output, ws)) { // parse file , display each of nodes. while (reader.read()) { switch (reader.nodetype) { case xmlnodetype.element: writer.writestartelement(reader.name); break; case xmlnodetype.text: writer.writestring(reader.value); break; case xmlnodetype.xmldeclaration: case xmlnodetype.processinginstruction: writer.writeprocessinginstruction(reader.name, reader.value); break; case xmlnodetype.comment: writer.writecomment(reader.value); break; case xmlnodetype.endelement: writer.writefullendelement(); break; } } } }
i believe error thrown on second parent element. how can avoid error? appreciated.
you need enclose <parent>
elements in surrounding element xml documents can have 1 root node:
<parents> <!-- i've added tag --> <parent> <child> text </child> </parent> <parent> <child> <grandchild> text </grandchild> <grandchild> text </grandchild> </child> <child> text </child> </parent> <parents> <!-- i've added tag -->
as you're receiving markup somewhere else, rather generating yourself, may have treating response string , wrapping appropriate tags, prior attempting parse xml.
so, you've couple of choices:
- get provider of web service return actual xml has 1 root node
- pre-process xml, i've suggested above, add root node
- pre-process xml split multiple chunks (i.e. 1 each
<parent>
node) , process each distinct xml document
Comments
Post a Comment