简体   繁体   中英

XML append node with main element

Hi all I have my XML as follows

<?xml version="1.0" encoding="utf-8"?>
<ApplicantDetails>
</ApplicantDetails>

I am adding dynamically the nodes based on few searches as follows

XmlDocument xDoc = new XmlDocument();
xDoc.Load(path);
XmlElement root = xDoc.DocumentElement;
XmlElement elem = null;
XmlElement e = xDoc.CreateElement("ApplicantData");
e.InnerText = string.Empty;
root.AppendChild(e);
xDoc.Save(path);
elem = xDoc.CreateElement("Mobile");
elem.InnerText = txtMobile.Text;
XmlNode node = root.SelectSingleNode("ApplicantData");
node.AppendChild(elem);
xDoc.Save(path);

Which is giving my XML as follows

<?xml version="1.0" encoding="utf-8"?>
<ApplicantDetails>
  <ApplicantData>
    <Mobile>1234567890</Mobile>
  </ApplicantData>
</ApplicantDetails>

Now I would like to add a new node as follows

<ApplicantData>
    <Mobile>1000000</Mobile>
</ApplicantData>

But with the code I have written it is appending as follows

<?xml version="1.0" encoding="utf-8"?>
<ApplicantDetails>
  <ApplicantData>
    <Mobile>1234567890</Mobile>
    <Aadhar>
    </Aadhar>
    <Mobile>1234567801</Mobile>
  </ApplicantData>
  <ApplicantData>
  </ApplicantData>
</ApplicantDetails>

Instead of XmlElement use XmlNode

XmlNode ApplicantData = xDoc.CreateElement("ApplicantData");
XmlNode elem = null;
XmlNode e = xDoc.CreateElement("ApplicantData");
e.InnerText = string.Empty;
elem = xDoc.CreateElement("Mobile");
elem.InnerText = txtMobile.Text;
ApplicantData.AppendChild(elem);
xDoc.DocumentElement.AppendChild(ApplicantData);                    
xDoc.Save(path);

You can use the below code to create dynamic xml.

XElement xmldata = new XElement("ApplicantDetails",
           new XElement("ApplicantData", new XElement("Mobile", 1234567890)),
           new XElement("ApplicantData", new XElement("Mobile", 1234567801))
        );

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