如何使用c#删除和添加xml特定节点?
问题描述:
我有XML格式。我想从xml节点中删除特定的标签。怎么做。如何使用c#删除和添加xml特定节点?
XML格式:
<?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>
我想删除TagName1节点&为TagName3增加新的标记名称。如何删除和添加新节点。
请帮我解决这个问题。
答
这应该这样做。 xmlInput是你的xml作为字符串,使用xpath来选择特定的元素。 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();
}
答
我会建议使用Linq
到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")));
检查Demo
看起来像它的副本:http://*.com/questions/2470103/best-way -to-manipulate-xml-in-net检查一般的linqToXml。 –