7

I have an 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);
}
4

3 回答 3

10

必须在父节点上调用 InsertAfter(在您的情况下为“NonFuel”)。

nonFuel.InsertAfter(xmlRecordNo, dispute);

它可能看起来有点令人困惑,但它是这样读取的:您要求父节点 (nonFuel) 在现有节点 (dispute) 之后添加一个新节点 (xmlRecordNo)。

一个完整的例子在这里:

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);
于 2013-05-29T08:51:24.030 回答
5
XmlDocument doc = new XmlDocument();
doc.Load("input.xml");

XmlElement records = doc.CreateElement("Records");
records.InnerText = Guid.NewGuid().ToString();
doc.DocumentElement.AppendChild(records);

doc.Save("output.xml"); // if you want to overwrite the input use doc.Save("input.xml");
于 2013-05-29T08:46:47.453 回答
0

使用“AppendChild”方法 - 添加为最后一个元素。

于 2016-12-28T11:16:24.187 回答