如何从XML元素中获取子元素和孙元素?

时间:2022-11-27 23:39:39

So, I have an XElement, that contains multiple child elements. I can successfully declare the XElement, and write it to a file:

所以,我有一个包含多个子元素的XElement。我可以成功声明XElement,并将其写入文件:

Test.project:

Test.project:

<?xml version="1.0" encoding="utf-8"?>
<project>
    <child>
        <grand-child1>
            <great-grand-child1>Hello There!</great-grand-child1>
            <great-grand-child2>Hello World!</great-grand-child2>
        </grand-child1>
        <grand-child2>Testing 123...</grand-child2>
    </child>
</project>

Then I'm trying to read from the file. I searched for ways to get child and grand-child nodes, and found I can use XElement.XPathSelectElement(). The problem is, Visual C# doesn't recognize XPathSelectElement as a method for an XElement. I've searched for usage examples for the method, and they all say to use XElement.XPathSelectElement.

然后我试图从文件中读取。我搜索了获取子节点和子节点的方法,并发现我可以使用XElement.XPathSelectElement()。问题是,Visual C#无法将XPathSelectElement识别为XElement的方法。我搜索了该方法的用法示例,他们都说要使用XElement.XPathSelectElement。

For example, I tried:

例如,我尝试过:

x_el = new XElement("project",
    new XElement("child",
        new XElement("grand-child", "Hello World!")
);

string get_string = x_el.XPathSelectElement("child/grand-child");

...but XPathSelectElement is not recognized. What am I doing wrong?

...但是无法识别XPathSelectElement。我究竟做错了什么?

1 个解决方案

#1


4  

You need to add System.Xml.XPath namespace as well like

您还需要添加System.Xml.XPath命名空间

using System.Xml.XPath;

after that try below

之后尝试下面

x_el = new XElement("project",
    new XElement("child",
        new XElement("grand-child", "Hello World!")
));
// XPathSelectElement method return XElement not string , use var or XElement 
XElement element = x_el.XPathSelectElement("child/grand-child");
string get_string = element.ToString()

Or

要么

var get_string = x_el.XPathSelectElement("child/grand-child").ToString();

#1


4  

You need to add System.Xml.XPath namespace as well like

您还需要添加System.Xml.XPath命名空间

using System.Xml.XPath;

after that try below

之后尝试下面

x_el = new XElement("project",
    new XElement("child",
        new XElement("grand-child", "Hello World!")
));
// XPathSelectElement method return XElement not string , use var or XElement 
XElement element = x_el.XPathSelectElement("child/grand-child");
string get_string = element.ToString()

Or

要么

var get_string = x_el.XPathSelectElement("child/grand-child").ToString();