Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an XmlDocument that already exists and is read from a file.

I would like to add a chunk of Xml to a node in the document. Is there a good way to create and add all the nodes without cluttering my code with many .CreateNote and .AppendChild calls?

I would like some way of making a string or stringBuilder of a valid Xml section and just appending that to an XmlNode.

ex: Original XmlDoc:

<MyXml>
   <Employee>
   </Employee>
</MyXml>

and, I would like to add a Demographic (with several children) tag to Employee:

<MyXml>
   <Employee>
      <Demographic>
         <Age/>
         <DOB/>
      </Demographic>
   </Employee>
</MyXml>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
520 views
Welcome To Ask or Share your Answers For Others

1 Answer

I suggest using XmlDocument.CreateDocumentFragment if you have the data in free form strings. You'll still have to use AppendChild to add the fragment to a node, but you have the freedom of building the XML in your StringBuilder.

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(@"<MyXml><Employee></Employee></MyXml>");

XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment();
xfrag.InnerXml = @"<Demographic><Age/><DOB/></Demographic>";

xdoc.DocumentElement.FirstChild.AppendChild(xfrag);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...