在 c# 中重新排列 Xml 子节点
本文关键字:排列 Xml 子节点 新排列 | 更新日期: 2023-09-27 18:36:53
我在重新排列 xml 数据时遇到问题。
我有这样的
<PolicySummary>
<InsuredName></InsuredName>
<PolicyNumber></PolicyNumber>
<PrevPolicyNumber></PrevPolicyNumber>
<PolicyState></PolicyState>
<TotalPremium></TotalPremium>
<Address></Address>
<Address1></Address1>
<City></City>
<State></State>
<Zip></Zip>
</PolicySummary>
但我想要这样
<PolicySummary>
<InsuredName></InsuredName>
<PolicyNumber></PolicyNumber>
<PrevPolicyNumber></PrevPolicyNumber>
<PolicyState></PolicyState>
<TotalPremium></TotalPremium>
<MailingAddress>
<Address></Address>
<Address1></Address1>
<City></City>
<State></State>
<Zip></Zip>
</MailingAddress>
</PolicySummary>
我希望邮寄地址节点应该包含地址,地址1,城市,州,邮政编码,任何人都可以提供帮助。我尝试了很多方法,例如附加子级,之后插入但没有任何效果
我试图获取节点并插入邮寄地址并附加它
XmlDocument policysummary = new XmlDocument();
XmlNode copynode = policysummary.ImportNode(
xmlautoDocument.SelectSingleNode("PolicySummary/TotalPremium"), true);
XmlNode premium = policysummary.SelectSingleNode("TotalPremium");
XmlNode addressss = policysummary.CreateNode(XmlNodeType.Element,
"Mailingaddress", null);
XmlNode root2 = policysummary.DocumentElement;
premium.InsertAfter(addressss, premium);
使用 XDocument
而不是 XmlDocument
尝试此操作:
var xDoc = XDocument.Parse(xmlString)
var root = xDoc.Element("PolicySummary");
var totalPremium = root.Element("TotalPremium");
//get all values you want to put in mailing address
var address = root.Element("Address");
//...
var mailingAddress = new XElement("MailingAddress");
mailingAddress.Add(address);
//Add mailing address after total premium
totalPremium.AddAfterSelf(mailingAddress);
//Remove all values you inserted in mailing address
address.Remove();
//If you want to save it somewhere
xDoc.Save(fileName);