0

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.

StepUp
  • 36,391
  • 15
  • 88
  • 148
dhamo
  • 181
  • 5
  • 14

2 Answers2

0

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();
}
Sammy
  • 1
  • 1
0

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

Hari Prasad
  • 16,716
  • 4
  • 21
  • 35