如何在节点之间插入和删除Xml文档片段?

时间:2015-02-17 10:33:30

标签: c# asp.net xml

如何在节点之间插入和删除Xml文档片段。我想在特定标记内添加和删除xml片段。

XML:

<project> 
    <ItemGroup>
       <Content Include="App_LocalResources" />
    </ItemGroup>
    <ItemGroup>
       <EmbeddedResource Include="lice.pccx" />
    </ItemGroup>
    <Import Project="$(MSBuildBinPath)" />
    <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0" />
</project>

我想在<EmbeddedResource Include=licenses.licx />内插入<ItemGroup>片段 之后我想删除<EmbeddedResource Include="lice.pccx" />

2 个答案:

答案 0 :(得分:0)

var xDoc = XElement.Load("FilePath");
if (xDoc == null)
   return;

var myNewElement = new XElement("ElementName"
   new XAttribute("AttributeName", value1),
   new XAttribute("AttributeName", value2)
   //And so on ...
);
xDoc.Add(myNewElement);
xDoc.Save("FilePath");

//

doc.Root.Descendants(actualNode.Parent.Name)
        .Elements(actualNode.Name)
        .Remove();

答案 1 :(得分:0)

using System.Xml.XPath;

var xml = XElement.Load(xmlFile);
//var xml = XElement.Parse(xmlString); //in case of loading from string
var liceElement = xml.XPathSelectElement("//EmbeddedResource[@Include='lice.pccx']");
liceElement.Remove();
//liceElement.Parent.Remove(); //if you would like to remove the whole 'ItemGroup' 
xml.Add(new XElement("ItemGroup",
        new XElement("EmbeddedResource",
            new XAttribute("Include", "licenses.licx"))));

xml.ToString();

Here你可以找到一些有用的xpath示例。