将属性添加到特定的XML标记C#

时间:2018-01-01 04:52:25

标签: c# xml

我有如下的XML

        <RESPONSE>
            <DATA id="1"/>
            <DATA id="2"/>
            <DATA id="3"/>
            <DATA id="4"/>
        </RESPONSE>

如何将属性value = 200添加到DATA id =2

最后我正在寻找下面的XML

        <RESPONSE>
            <DATA id="1"/>
            <DATA id="2" value = "200"/>
            <DATA id="3"/>
            <DATA id="4"/>
        </RESPONSE>

提前致谢:)

3 个答案:

答案 0 :(得分:0)

尝试以下代码,

        string testData = @" <RESPONSE>
                    <DATA id=""1""/>
                    <DATA id = ""2""/> 
                    <DATA id = ""3""/>  
                    <DATA id = ""4""/>   
                </RESPONSE>";

        XDocument xdc = XDocument.Parse(testData);
        var elementes = xdc.Descendants("DATA")
            .Where(e => e.Attribute("id") != null ? e.Attribute("id").Value == "2" : false);

        foreach (XElement element in elementes)
        {
            XAttribute attribute = new XAttribute("value", "200");
            element.Add(attribute);
        }

        var str = xdc.ToString();

答案 1 :(得分:0)

尝试以下代码段。

void Main()
{
    string data= @" <RESPONSE>
                    <DATA id=""1""/>
                    <DATA id = ""2""/> 
                    <DATA id = ""3""/>  
                    <DATA id = ""4""/>   
                </RESPONSE>";

    XDocument xml = XDocument.Parse(data);

    var elements = from x in xml.Descendants("DATA")
                   where  x.Attribute("id").Value == "2" 
                   select x;
    foreach (XElement element in elements)
    {
        XAttribute attribute = new XAttribute("value", "200");
        element.Add(attribute);
    }


    var str = xml.ToString();
    Console.WriteLine(str);
}

答案 2 :(得分:0)

试试这个

 var xml = @"<RESPONSE>
                <DATA id=""1""/>
                <DATA id=""2""/> 
                <DATA id=""3""/>  
                <DATA id=""4""/>   
            </RESPONSE>";
        var data = XElement.Parse(xml);
        data.Elements("DATA").Where(x=>x.Attribute("id")?.Value== "2")?.FirstOrDefault()?.SetAttributeValue("value","200");