简体   繁体   中英

Rearrange the Xml child node in c#

I have problem in rearranging xml data.

I have like this

<PolicySummary>
    <InsuredName></InsuredName>
    <PolicyNumber></PolicyNumber>
    <PrevPolicyNumber></PrevPolicyNumber>
    <PolicyState></PolicyState>
    <TotalPremium></TotalPremium>

    <Address></Address>
    <Address1></Address1>
    <City></City>
    <State></State>
    <Zip></Zip>
</PolicySummary>

But I want like this

 <PolicySummary>
     <InsuredName></InsuredName>
     <PolicyNumber></PolicyNumber>
     <PrevPolicyNumber></PrevPolicyNumber>
     <PolicyState></PolicyState>
     <TotalPremium></TotalPremium>
     <MailingAddress>
         <Address></Address>
         <Address1></Address1>
         <City></City>
         <State></State>
         <Zip></Zip>
     </MailingAddress>
</PolicySummary>

I want mailing address node should contain address ,address1,city, state, zip can any one help. I tried many way like append child , insert after but nothing is worked

I tried to take the node and insert the mailing address and append it

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

Try this using XDocument instead of 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM