1

I am creating an XML object in c# and have html strings that I would like to parse into XElements in order to insert them, however I do not want to have to wrap them in a parent element as they are intended to be inserted into one already.

Html:

<p>Hello world</p><br /><p>Second <b>Line</b></p>

Intended Xml:

<p>Hello world</p>
<br />
<p>Second <b>Line</b></p>

At the moment the only way I can do this is if I use code below, however I don't want the outer tag

XElement.Parse("<parenttag>" + html + "</parenttag>") 

NB. These elements will be inserted into a parent element to form correct xml, my intended output for this html string is an array of xml elements ( ie 2 p elements and a br)

1
  • 3
    If you are going to downvote please provide some context, I am unaware of what is wrong with this question.. is it against rules of xml? Commented Jul 22, 2015 at 10:57

1 Answer 1

3

Once you've parse the string successfully by wrapping in an outer tag you should call .Elements() which will return the children on the element.

var html = "<p>Hello world</p><br /><p>Second <b>Line</b></p>";
var root = XElement.Parse("<parenttag>" + html + "</parenttag>")
var children = root.Elements();
// children.Count() == 3
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers this worked. For some reason completely avoided checking the properties of the root element, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.