简体   繁体   English

如果只有xml数据可用,如何使用LINQ to XML插入新节点?

[英]How to Insert a New Node Using LINQ to XML when only xml data is available?

I have an xml file with the below structure: 我有一个xml文件,其结构如下:

<connections>
  <connection>   
    <serverName>serverName1</serverName>
    <dbName>dbName1</dbName>   
  </connection>
</connections>

I have a new connection as text data as shown below: 我有一个新的连接作为文本数据,如下所示:

var xml="<connection><serverName>serverName2</serverName><dbName>dbName2</dbName></connection>";

var xDocument = XDocument.Load(HttpContext.Current.Server.MapPath(this.XmlDataFilePath));

How could I insert this new node to my document? 我怎么能将这个新节点插入我的文档?

I tried this but it failed: 我尝试了这个,但它失败了:

 xDocument.Root.AddAfterSelf(xml);

 xDocument.Save(HttpContext.Current.Server.MapPath(this.XmlDataFilePath));

Thanks, 谢谢,

Parse the XML into an XElement and then add that: 将XML解析为XElement,然后添加:

var element = XElement.Parse(xml);
xDocument.Root.Add(element);

Note this is not AddAfterSelf - you can't add a second root element as the peer of the first one. 请注意,这不是 AddAfterSelf - 您不能添加第二个根元素作为第一个根元素。 The code above will add a new child element after any existing ones, within the root element. 上面的代码将任何现有的后面添加一个新的子元素,根元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM