在C#中从StringBuilder中删除XML节点

时间:2014-04-16 14:18:26

标签: c# asp.net xml stringbuilder

我在StringBuilder xml中有结构节点,现在我想删除一些包含某些年份的节点,例如我想要删除具有这种结构的所有节点:

<dropDownValue caption='2013' key='2013'>及其中的所有节点

我的xml代码:

<dropDownValue caption='2013' key='2013'>
    <dropDown default='sdrive23i.aspx#ulTopMenu'>
        <description caption='Модификация'>
        <modifyResource placeholder='modification'/>
        </description>
        <dropDownValue caption='sDrive23i' key='sdrive23i.aspx#ulTopMenu'/>
        <dropDownValue caption='sDrive30i' key='sdrive30i.aspx#ulTopMenu'/>
        <dropDownValue caption='sDrive35i' key='sdrive35i.aspx#ulTopMenu'/>
    </dropDown>
</dropDownValue>


<dropDownValue caption='2013' key='2013'>
    <dropDown default='30d.aspx#ulTopMenu'>
        <description caption='Модификация'>
            <modifyResource placeholder='modification'/>
        </description>
        <dropDownValue caption='3.0D' key='30d.aspx#ulTopMenu'/>
        <dropDownValue caption='3.6' key='36.aspx#ulTopMenu'/>
        <dropDownValue caption='4.8GTS' key='48gts.aspx#ulTopMenu'/>
        <dropDownValue caption='4.8S' key='48s.aspx#ulTopMenu'/>
        <dropDownValue caption='4.8Turbo S' key='48turbos.aspx#ulTopMenu'/>
    </dropDown>
</dropDownValue>


<dropDownValue caption='2013' key='2013'>
    <dropDown default='27.aspx#ulTopMenu'>
        <description caption='Модификация'>
            <modifyResource placeholder='modification'/>
        </description>
        <dropDownValue caption='2.7' key='27.aspx#ulTopMenu'/>
        <dropDownValue caption='S 3.4' key='s34.aspx#ulTopMenu'/>
    </dropDown>
</dropDownValue>

<dropDownValue caption='2013' key='2013'>
    <dropDown default='4s_4_8.aspx#ulTopMenu'>
        <description caption='Модификация'>
            <modifyResource placeholder='modification'/>
        </description>
        <dropDownValue caption='4S 4.8' key='4s_4_8.aspx#ulTopMenu'/>
        <dropDownValue caption='S 4.8' key='s_4_8.aspx#ulTopMenu'/>
        <dropDownValue caption='Turbo 4.8' key='turbo_4_8.aspx#ulTopMenu'/>
    </dropDown>
</dropDownValue>

1 个答案:

答案 0 :(得分:3)

使用XDocument如何:

var xml = XDocument.Load("yourfile.xml");

xml.Descendants("dropDownValue")
   .Where(e => e.Attribute("caption").Value == "2013" && e.Attribute("key").Value == "2013").Remove();

//your xml as a string again
var stringXml = xml.ToString();

或者使用XmlDocument:

var xmlDoc = new XmlDocument();
xmlDoc.Load("file.xml");

XmlNodeList nodes = xmlDoc.SelectNodes("//dropDownValue[@caption='2013' and @key='2013']");

foreach (XmlNode node in nodes)
    node.ParentNode.RemoveChild(node);

//your xml as a string again
var xmlDocString = xmlDoc.OuterXml;