简体   繁体   中英

How to remove and add xml particular node using c#?

I have XML format. I would like to remove particular tag from xml node. How to do it.

XML format:

<?xml version="1.0"?>
<EmployeeResults>
  <MainArea>
    <CreationDateTime>2016-06-28T06:10:51.5215523Z</CreationDateTime>
  </MainArea>
  <SubArea>
    <Show>
      <ID>TEST1</ID>
    </Show>
    <ProductionPerformance>
      <ID>Fabrication_ERP_MES_DEM_1-A</ID>
      <ProductionResponse>
        <ID>123</ID>        
        <StartTime>0001-01-01T00:00:00Z</StartTime>
        <EndTime>0001-01-01T00:00:00Z</EndTime>
        <EmployeeResponse>
          <ID>LotEmployeeResponse</ID>          
          <ActualStartTime>2016-06-28T05:58:41.673Z</ActualStartTime>
          <ActualEndTime>0001-01-01T00:00:00Z</ActualEndTime>            
            <Quantity>
              <QuantityString>1</QuantityString>
            </Quantity>
          </MaterialActual>
          <TagName1>
            <ID>Test1</ID>
          </TagName1>
          <TagName2>
            <ID>Test2</ID>
          </TagName2>
        </EmployeeResponse>
      </ProductionResponse>
    </ProductionPerformance>
  </SubArea>
</EmployeeResults>

I would like to remove TagName1 node & add new tag name for TagName3. How to remove and add new node.

Please help me to solve this.

This should do it. xmlInput is your xml as string, use xpath to select specific element. https://msdn.microsoft.com/en-us/library/d271ytdx(v=vs.110).aspx

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlInput);

XmlNode node = doc.SelectSingleNode("XPATh");


if (node != null)
{
   node.Remove();
}

I would suggest using Linq to Xml

XDocument doc= XDocument.Load(filepath);

// Remove the element
doc.Descendants("TagName1")
   .Remove();

// Add new Element - Test3
doc.Descendants("EmployeeResponse")
   .ElementAtOrDefault(0)
   .Add(new XElement("TagName3", new XElement("ID", "Test3")));

Check the Demo

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