问题
I have an xml document which is roughly as follows
<Gov>
<Head>
<address></address>
<address></address>
</Head>
<Body>
<line1></line1>
<line1></line1>
</Body>
<Gov>
I need to copy everything in the body(and including) to a new XDocument. What is the best way to
回答1:
Here is an example of copying data "xml" from one document to another.With selection of personalized node
First you need convert Xdocument to XmlDocument:
using System;
using System.Xml;
using System.Xml.Linq;
namespace MyTest
{
internal class Program
{
private static void Main(string[] args)
{
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml("<Root><Child>Test</Child></Root>");
var xDocument = xmlDocument.ToXDocument();
var newXmlDocument = xDocument.ToXmlDocument();
Console.ReadLine();
}
}
public static class DocumentExtensions
{
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using(var xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
return xmlDocument;
}
public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
using (var nodeReader = new XmlNodeReader(xmlDocument))
{
nodeReader.MoveToContent();
return XDocument.Load(nodeReader);
}
}
}
}
And now simplified copy with XmlDocument
XmlDocument doc1 = new XmlDocument();
doc1.LoadXml(@"<Hello>
<World>Test</World>
</Hello>");
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml(@"<Hello>
</Hello>");
XmlNode copiedNode = doc2.ImportNode(doc1.SelectSingleNode("/Hello/World"), true);
doc2.DocumentElement.AppendChild(copiedNode);
more information here:
- http://blog.project-sierra.de/archives/1050
- Copy Xml element to another document in C#
- Converting XDocument to XmlDocument and vice versa
I hope this help you.
回答2:
Read in the input XML into one XDocument
and construct a second, passing in the node you are interested in:
XDocument newDoc = new XDocument(XDocument.Load("input.xml").Descendants("Body").First());
来源:https://stackoverflow.com/questions/16584641/copying-part-of-an-xml-document-to-another-document-using-xdocument