我有一个名为“Dispute”的元素,并希望在元素下面添加新的元素名称“Records”.
例如:当前的XML采用这种格式
例如:当前的XML采用这种格式
<NonFuel> <Desc>Non-Fuel</Desc> <Description> </Description> <Quantity/> <Amount/> <Additional/> <Dispute>0</Dispute> </NonFuel>
需要添加有争议的新元素.
<NonFuel> <Desc>Non-Fuel</Desc> <Description> </Description> <Quantity/> <Amount/> <Additional/> <Dispute>0</Dispute> <Records>01920</Records> </NonFuel>
更新的代码:
尝试执行以下代码但收到错误“参考节点不是此节点的子节点”:
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”).
原文链接:https://www.f2er.com/xml/293120.htmlnonFuel.InsertAfter(xmlRecordNo,dispute);
它可能看起来有点令人困惑,但它以这种方式读取:您要求父节点(nonFuel)在现有节点(争议)之后添加新节点(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);