[英]C# Adding a root to an XDocument
I have a string that contains an XML, lets say like this: 我有一个包含XML的字符串,让我们这样说:
<Novels>
<Book>
<Title>Cat in hat</Title>
<Price>12</Price>
</Book>
</Novels>
I want to make an XDocument that looks like this: 我想制作一个如下所示的XDocument:
<Booklist>
<Novels>
<Book>
<Title>Cat in hat</Title>
<Price>12</Price>
</Book>
</Novels>
</Booklist>
I can load the xml string into an XDocument using XDocument doc = XDocument.Parse(xmlString);
我可以使用
XDocument doc = XDocument.Parse(xmlString);
将xml字符串加载到XDocument中XDocument doc = XDocument.Parse(xmlString);
How would I load the document under a new root. 如何在新根目录下加载文档。 I can think of something like creating a new XDocument with the root I want and then using a for loop to add the nodes as children, but is there an easier way of doing this?
我可以想到用我想要的根创建一个新的XDocument,然后使用for循环将节点添加为子节点,但是有更简单的方法吗?
XDocument yourResult = new XDocument(new XElement("Booklist", doc.Root));
var doc = new XDocument(new XElement("Booklist", source.Root));
It does not require any parsing at all. 它根本不需要任何解析。 There is a deep copy of XElement made, so there is also no references between old and new documents.
有一个XElement的深层副本,因此旧文档和新文档之间也没有引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.