如何使用xml文档在现有元素下添加新元素 [英] How to add new element below existing element using xml Document

查看:192
本文介绍了如何使用xml文档在现有元素下添加新元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元素名称为Dispute,并且要在元素下面添加新的元素名称Records。

I have a element Name "Dispute" and want to add new element name "Records" below the element.

Eg: The current Xml is in this format
<NonFuel>
            <Desc>Non-Fuel</Desc>
            <Description>
            </Description>
            <Quantity/>
            <Amount/>
            <Additional/>
        <Dispute>0</Dispute>
 </NonFuel>

需要添加有争议的新元素。

Need to add new element under dispute.

<NonFuel>
            <Desc>Non-Fuel</Desc>
            <Description>
            </Description>
            <Quantity/>
            <Amount/>
            <Additional/>
            <Dispute>0</Dispute>
            <Records>01920</Records>
     </NonFuel>

更新代码:
尝试执行以下代码但获取错误引用节点不是这个节点的子节点:

Updated Code: Tried doing the following Code but getting error "The reference node is not child of this node":

 XmlDocument xmlDoc=new XmlDocument()
 xmlDoc.LoadXml(recordDetails);
 XmlNodeList disputes = xmlDoc.GetElementsByTagName(disputeTagName);
 XmlNode root = xmlDoc.DocumentElement;
 foreach (XmlNode disputeTag in disputes)
  {
  XmlElement xmlRecordNo = xmlDoc.CreateElement("RecordNo");
  xmlRecordNo.InnerText = Guid.NewGuid().ToString();
  root.InsertAfter(xmlRecordNo, disputeTag);
   }


推荐答案

InsertAfter必须在父节点(在您的情况下为NonFuel)。

InsertAfter must be called on the parent node (in your case "NonFuel").

nonFuel.InsertAfter(xmlRecordNo, dispute);

它可能看起来有点混乱,但它读起来这样:你要求父节点

It may look a little confusing but it reads this way: you are asking the parent node (nonFuel) to add a new node (xmlRecordNo) after an existing one (dispute).

一个完整的例子如下:

XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(@"<NonFuel><Desc>Non-Fuel</Desc><Description></Description><Quantity/><Amount/><Additional/><Dispute>0</Dispute></NonFuel>");

XmlNode nonFuel = xmlDoc.SelectSingleNode("//NonFuel");
XmlNode dispute = xmlDoc.SelectSingleNode("//Dispute");


XmlNode xmlRecordNo=  xmlDoc.CreateNode(XmlNodeType.Element, "Records", null);
xmlRecordNo.InnerText = Guid.NewGuid().ToString();
nonFuel.InsertAfter(xmlRecordNo, dispute);

这篇关于如何使用xml文档在现有元素下添加新元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆