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



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

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

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

然后,用户可能希望从information/machine中的name键中检索值。

有没有办法使用XDocument/XPath我可以查找用户想要的值,而无需知道/编码文档的架构?

我最初的想法是使用一种利用XElement项的递归函数形式来完成文档,但我觉得应该有一个更简单/更干净的解决方案,不需要我滚动自己的查找代码。

我也尝试了类似的东西

var doc = XDocument.Load("C:PathtoXMLfile.xml");
// Split the parent keys string
XElement elem = doc.Root.XPathSelectElement("path/to/key");
if (elem != null && elem.Attribute("wantedKeyName") != null)
replace = elem.Attribute("wantedKeyName").Value;

elem始终为空。我假设我定义路径或使用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;
}

这是使用的方法:

var node = SearchNode(doc.ChildNodes, "compiler");
var node1 = SearchNodeByPath(doc.ChildNodes, "compilers/compiler");

事实证明我使用XPathSelectElement的解决方案是正确的方法,我只需要在path/to/key字符串前面加上//即可。

我最终使用的以下代码这样做并去除值外部周围的任何空格(以防值与开始标记位于单独的行上。

// 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();

最新更新