0

我确实有一个看起来像这样的 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 值测试下。如何在名称值 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")

            )
        )
    );

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

问候马丁

4

1 回答 1

0

Element("name") returns first element that matches the name. That's why you to query for your <name> element.

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

It should do the trick. Whole code would look like that:

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")

            )
        )
    );
于 2013-08-21T17:26:52.077 回答