0

我在重新排列 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、城市、州、邮编可以帮助任何人。我尝试了很多方法,比如 append child , insert after 但没有任何效果

我试图获取节点并插入邮寄地址并附加它

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);
4

1 回答 1

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);
于 2013-10-24T13:11:06.660 回答