我在重新排列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);
答案 0 :(得分:1)
使用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);