使用.net从XElement获取特定节点

时间:2015-09-30 15:19:54

标签: c# xml

我有以下xml。我只想要<Profile>元素。

<Profiles>
<ProfileInfo>
<Profile>
<name>test</name>
<age>2</age>
</Profile>

</ProfileInfo>
</Profiles>

我试过

var nodes1 = nodes.Elements().Where(x => x.Element("Profiles") != null).ToList();
foreach (var node in nodes1)
    node.Remove();

我也尝试直接获取值

var nodes = xmlDocumentWithoutNs.Elements()
    .Where(x => x.Element("Profile") != null)
    .ToList();

但这并不能得到我想要的数据。我需要更改什么来获取我想要的数据?

我希望这种形式的结果(表示):

<Profile>
    <name>test</name>
    <age>2</age>
</Profile>

3 个答案:

答案 0 :(得分:2)

以下代码段将获取第一个子配置文件元素的值:

var someData = doc.Root.DescendantsAndSelf("Profile").First();

someData的值为:

<Profile>
  <name>test</name>
  <age>2</age>
</Profile>

答案 1 :(得分:0)

此示例可能有所帮助:

XElement root = XElement.Parse(@"
    <Profiles>
        <ProfileInfo>
            <Profile>
            <id>5</id>
            </Profile>
        </ProfileInfo>
        <ProfileInfo>
            <Profile>
            <id>6</id>
            </Profile>
        </ProfileInfo>
    </Profiles>
");


var node2 = root.Elements("ProfileInfo").ToList();
Console.WriteLine (node2[0].Element("Profile").Element("id").Value.ToString());

答案 2 :(得分:0)

使用XML Linq尝试此操作。在这种情况下,将元素添加到新的XML对象会更容易。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
                "<Profiles>" +
                    "<ProfileInfo>" +
                    "<Profile>" +
                    "<name>test1</name>" +
                    "<age>2</age>" +
                    "</Profile>" +
                    "<Profile>" +
                    "<name>test2</name>" +
                    "<age>2</age>" +
                    "</Profile>" +
                    "<Profile>" +
                    "<name>test3</name>" +
                    "<age>2</age>" +
                    "</Profile>" +
                    "</ProfileInfo>" +
                    "</Profiles>";

            XElement element = XElement.Parse(input);

            XElement newElement = null;

            foreach (XElement profile in element.Descendants("Profile"))
            {
                if (newElement == null)
                {
                    newElement = profile;
                }
                else
                {
                    newElement.Add(profile);
                }
            }
        }
    }
}
​