9

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

测试项目:

<?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>

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

例如,我试过:

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

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

...但XPathSelectElement未被识别。我究竟做错了什么?

4

1 回答 1

5

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

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();
于 2013-08-22T03:39:23.217 回答