1

Can someone tell me how to add extra root to loaded xml file in c#?

Now i have:

<object>
<obj_name>hero1</obj_name>
<field>
</field>
</object>
<object>
<obj_name>hero2</obj_name>
<field>
</field>
</object>

After i would like to have:

<objects>
<object>
<obj_name>hero1</obj_name>
<field>
</field>
</object>
<object>
<obj_name>hero2</obj_name>
<field>
</field>
</object>
</objects>

My code:

        //Create XmlDocument instance
        XmlDocument doc = new XmlDocument();

        //Before loading xml file whtie spaces are allowed
        doc.PreserveWhitespace = false;

        //Loading xml file
        doc.Load(@"..\..\input.xml");

        //Deleting white spaces
        doc.PreserveWhitespace = true;
kjhughes
  • 106,133
  • 27
  • 181
  • 240
Drax
  • 63
  • 1
  • 1
  • 7

1 Answers1

2

What you have currently is not XML because two root elements are not allowed in XML.

Your title and opening question are inconsistent with your code. You already have two root elements, and you're trying to wrap them in a single root element so that you do have well-formed XML.

You cannot process non-well-formed XML with XML libraries (because it isn't XML); first you have to repair it. Read the file as text, add the wrapper root element, and then parse it as XML. For more details on dealing with problem "XML," see How to parse invalid (bad / not well-formed) XML?

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • One more question. Is it possible that I can interpret from the xml file only those fields I care about, i.e. I would like the xml file to be interpreted eg ,
    and I would not like it to be interpreted eg ??
    – Drax May 06 '19 at 19:50
  • 1
    You can process Non Well Formed Xml in Net. Use XmlReader and set XmlReaderSettings to : settings.ConformanceLevel = ConformanceLevel.Fragment; – jdweng May 06 '19 at 21:36
  • @jdweng: That's very good to know. I've added that helpful tip credited to you in my answer at [How to parse invalid (bad / not well-formed) XML?](https://stackoverflow.com/a/44765546/290085). Thank you. – kjhughes May 06 '19 at 23:26
  • @Drax: "Interpret" is per your application, so of course there are ways to interpret or ignore XML elements or attributes. You'll have to clarify your goals and elaborate what you've tried in a new question, however, as comments aren't meant for that. Thanks. – kjhughes May 06 '19 at 23:59