C# 从任意键路径检索C中的XML值

C# 从任意键路径检索C中的XML值,c#,xml,xpath,linq-to-xml,C#,Xml,Xpath,Linq To Xml,我有一个项目,目前我正在实现对通过文档键中的任意/用户定义路径从XML文件读取值的支持 例如,如果文档如下所示: <information> <machine> <foo></foo> <name> test machine </name> <bar>spam</bar> </machine&

我有一个项目,目前我正在实现对通过文档键中的任意/用户定义路径从XML文件读取值的支持

例如,如果文档如下所示:

<information>
    <machine>
        <foo></foo>
        <name>
            test machine
        </name>
        <bar>spam</bar>
    </machine>
</information>

但元素总是空的。我假设我定义路径或使用XPathSelectElement的方式有问题,但我还没有解决它。

我发现使用XPathSelectElement的解决方案是正确的方法,我只需要在路径/到/键字符串前面加上//

static XmlNode SearchNode(XmlNodeList nodeList, string nodeName)
{
    for (int i = 0; i < nodeList.Count; i++)
    {
        if (nodeList[i].Name == nodeName)
        {
            return nodeList[i];
        }

        if (nodeList[i].HasChildNodes)
        {
            XmlNode node = SearchNode(nodeList[i].ChildNodes, nodeName);
            if (node != null)
            {
                return node;
            }
        }
    }

    return null;
}

static XmlNodeList SearchNodeByPath(XmlNodeList nodeList, string xPath)
{
    for (int i = 0; i < nodeList.Count; i++)
    {
        var nodes = nodeList[i].SelectNodes(xPath);
        if (nodes != null && nodes.Count > 0)
        {
            return nodes;
        }

        if (nodeList[i].HasChildNodes)
        {
            XmlNodeList innerNodes = SearchNodeByPath(nodeList[i].ChildNodes, xPath);
            if (innerNodes != null && innerNodes.Count > 0)
            {
                return innerNodes;
            }
        }
    }

    return null;
}
我最后使用的以下代码可以做到这一点,并去掉值外部的所有空格,以防值位于除开始标记之外的单独一行上

// xml is a struct with the path to the parent node (path/to/key)
// and the key name to look up
// Split the parent keys string
XElement elem = doc.Root.XPathSelectElement("//" + xml.KeyPath);
if (elem != null && elem.Element(xml.Key) != null)
    replace = elem.Element(xml.Key).Value.Trim();

XDocument doc=XDocument.LoadYOURXML.xml;var q=来自doc.Elementsinformation.Elementsmachine选择元素中的元素;foreach var item in q{string str=item.Elementname.Value;}@ershoaib如果我事先知道XML文件的模式,我会这么做,但是程序必须能够处理任何XML文件和其中的任何路径,而不知道其内容。如果不知道文件的内容,如何使用XPathSelectElementpath/to/key?在这种情况下,你不知道path@RPiAwesomeness可能您的实际XML包含名为xmlns的默认名称空间“属性”,比如这里的xmlns=一些名称空间uri。如果是这种情况,请参见:使用子体:列表元素=doc.genderantsname.ToList;
    var node = SearchNode(doc.ChildNodes, "compiler");
    var node1 = SearchNodeByPath(doc.ChildNodes, "compilers/compiler");
// xml is a struct with the path to the parent node (path/to/key)
// and the key name to look up
// Split the parent keys string
XElement elem = doc.Root.XPathSelectElement("//" + xml.KeyPath);
if (elem != null && elem.Element(xml.Key) != null)
    replace = elem.Element(xml.Key).Value.Trim();