Silverlight XML在特殊位置添加节点(使用LINQ)

时间:2013-08-21 17:24:32

标签: xml silverlight linq-to-xml

我有一个看起来像这样的XML

<root>
    <name value="test">
        <contact>
            <id>1</id>
            <Name>myname mylastname</Name>
            <phone>
                <number1_1>123456789</number1_1>
                <number2_1>987654321</number2_1>
            </phone>
        </contact>
        <contact>
            <id>2</id>
            <Name>myname mylastname</Name>
            <phone>
                <number1_2>123456789</number1_2>
                <number2_2>987654321</number2_2>
            </phone>
        </contact>
    </name>
    <name value="test1">
        <contact>
            <id>1</id>
            <Name>myname mylastname</Name>
            <phone>
                <number1_1>123456789</number1_1>
                <number2_1>987654321</number2_1>
            </phone>
        </contact>
    </name>
</root>

使用此代码我可以添加一个新节点,但它总是会在firstname值test下添加。如何在名称值test1下添加它?

xmldoc.Element("root").Element("Name").Add( 
    new XElement("contact",
            new XElement("id", "2"),
            new XElement("Name", "notset"),
            new XElement("phone",
                new XElement("number1_1", "notset"),
                new XElement("number2_1", "notset")

            )
        )
    );

有人可以给我提示或一行代码我怎么做!

关心马丁

1 个答案:

答案 0 :(得分:0)

Element("name")返回与名称匹配的第一个元素。这就是您查询<name>元素的原因。

.Elements("Name").First(x => (string)x.Attribute("value") == "test1")

它应该做的伎俩。整个代码看起来像这样:

xmldoc.Element("root")
      .Elements("Name").First(x => (string)x.Attribute("value") == "test1").Add( 
    new XElement("contact",
            new XElement("id", "2"),
            new XElement("Name", "notset"),
            new XElement("phone",
                new XElement("number1_1", "notset"),
                new XElement("number2_1", "notset")

            )
        )
    );