Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
I have to process a wannabe XML string.
It hasn't got a root element (for reasons unknown), but I can't do much about it.

So I decided to stick a dummy root node around the entire XML and then feed it into the XMLDocument.

The XML in question looks like:
<mynode>
   blah
   <morenodes>
     blah
     blah
   </morenodes>
</mynode>
   blah
   <morenodes>
     blah
     blah
   </morenodes>

...


So to cheat, I decided to do
<root>
   <mynode>
     blah
     <morenodes>
       blah
       blah
     </morenodes>
   </mynode>
   <mynode>
     blah
     <morenodes>
       blah
       blah
     </morenodes>
   </mynode>
...
</root>


Thinking this is fairly straight forward, I did
string newString = "<root>" + oldString + "</root>";
XMLDocument xmlDolcument = new XMLDocument();
xmlDocument.Load(newString);


where oldString is where the original XML is found.

For some reason, the <Root> tag gets added OK, but the </Root> refuses to be added whatever I try.
What's so hard about string concatenation, and what am I doing that's so horribly wrong?

Please help!

[Edit] Formatting went wrong and the ending tag disappeared...
Posted
Updated 23-Feb-11 22:10pm
v2

Your code (even if I view the raw source of your question) doesn't add the ending tag!
Try:
C#
string newString = "<root>" + oldString + "</root>";
XMLDocument xmlDolcument = new XMLDocument();
xmlDocument.Load(newString);
 
Share this answer
 
Comments
Wayne Gaylard 24-Feb-11 3:25am    
Now the OP needs to combine both of these answers to come up with the correct solution - +5
Dalek Dave 24-Feb-11 3:42am    
Good Call.
PaulowniaK 24-Feb-11 4:11am    
The original question turned up a bit wrong, but the actual attempt looks pretty much like this suggestion.
Be careful, remember, strings are immutable, so if you have several "+" operations, whole string is copied again and again every time.

Prefer System.Text.StringBuilder.Append. If you want to concatenate statically fixed number of strings (not a loop), prefer string.Format.

—SA
 
Share this answer
 
Comments
CodingLover 24-Feb-11 3:03am    
this is a good point to consider actually. immutable stuff is a real mess. try to avoid "+" as much as possible
Sergey Alexandrovich Kryukov 24-Feb-11 3:31am    
Well, this is not mess, important feature -- functional approach.
--SA
Abhinav S 24-Feb-11 3:10am    
1) good point
2) no idea why your answer was downvoted.
3) 5 to fix this univote.
Sergey Alexandrovich Kryukov 24-Feb-11 3:12am    
Thank you.
Well, down-voters... savages...
--SA
Abhinav S 24-Feb-11 5:10am    
:)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900