如何使用C#从XML Document中删除标记?

时间:2012-11-16 11:35:11

标签: c# xmldocument

<sg>
       <userdata>
            <data>
             <tag name="gf" description="fg" nodeid="                                                      {2F2CC6951E2B4EEA979F357164CB73E5}" controllerid="" keytype="" mask="" track="widthsegment"    numkey="" interpolator="" frame="" aindex="1" number="1">
              <![CDATA[  //sg/objects/object[@id="          {2F2CC6951E2B4EEA979F357164CB73E5}"]/params/param[@name="widthsegment"]
               ]]> 
               </tag>
              <tag name="gf" description="fg" nodeid="               {2F2CC6951E2B4EEA979F357164CB73E5}" controllerid="" keytype="" mask="" track="widthsegment"                       numkey="" interpolator="" frame="" aindex="1" number="2">
               <![CDATA[  //sg/objects/object[@id="                         {2F2CC6951E2B4EEA979F357164CB73E5}"]/params/param[@name="widthsegment"]
              ]]> 
              </tag>
                </data>
               </userdata>
                    </sg>

我想删除“tag” - 标签,如何执行此操作

我是这样做的

updatedData.SelectSingleNode("//tag[@name='" + 1 + "']").RemoveAll(); 

但仍然标签来自此...我的意思是空标签..如何删除

之后

                   <sg>
                    <userdata>
                      <data>
                      <tag /> --- This is wat i want to remove... how to remove this
                       <tag name="gf" description="fg" nodeid="        {2F2CC6951E2B4EEA979F357164CB73E5}" controllerid="" keytype="" mask="" track="widthsegment"      numkey="" interpolator="" frame="" aindex="1" number="2">
                      <![CDATA[  //sg/objects/object[@id="           {2F2CC6951E2B4EEA979F357164CB73E5}"]/params/param[@name="widthsegment"]
                    ]]> 
                     </tag>
                      </data>

  

4 个答案:

答案 0 :(得分:1)

XmlNodeList nodes = updatedData.GetElementsByTagName("tagname");
foreach (XmlNode node in nodes)
{
    if (node.ChildNodes.Count == 0)
        node.RemoveAll();
    else
        UpdateDoc.InnerXml = node.OuterXml;
}

我解决了这个......

答案 1 :(得分:0)

var xmlDoc = XDocument.Load("filename.xml");
var element = (
    from x in xmlDoc.Root.Elements("elemnt-name")
    where x.Element("tage-name").Value == "xxxx"
    select x
    ).FirstOrDefault();
element.Remove();
xmlDoc .Save("filename.xml");

答案 2 :(得分:0)

你的XPath很奇怪:

"//tag[@name='" + 1 + "']"

它将选择tag属性值为1的所有name元素。您的示例中没有。

您还在使用SelectSingleNode,它只会选择一个节点。

如果您希望全部选择XPath,则XPath应为"//tag",而您应该使用SelectNodes代替。

答案 3 :(得分:0)

这是你如何将xdocument加载到XmlNodeList

 XDocument doc = XDocument.Load(@"C:\Users\sghaida\Documents\Visual Studio 2008\Projects\testing-ws-1\XMLParser\config.xml");
                XmlDocument xmlDoc = new XmlDocument();
                XmlNodeReader nodeReader = (XmlNodeReader)doc.CreateReader();
                xmlDoc.ReadNode(nodeReader);
                XmlNodeList xmlnodeList = xmlDoc.SelectNodes("node");