返回XML文件中第一个可能节点的内部文本

时间:2012-07-11 14:36:26

标签: c# xml linq xpath

我写了一个方法,专门搜索给定的完整xpath并返回内部文本。但由于我正在处理的文件都有唯一的节点名称,我想以某种方式做到只传递节点名称才能完成这项工作。

我的代码目前看起来如何:

public string FileInfo(string info)
{
    switch (info)
    {
        //FileInfo
        case "fileCreator":
            fileCreator = ztr.SelectSingleNode("//Document/FileInfo/Creator").InnerText;
            return fileCreator;
        case "fileName":
            fileName = ztr.SelectSingleNode("//Document/FileInfo/Name").InnerText;
            return fileName;
      //And so on with lots of other cases!!!

我怎样才能让它以某种方式来搜索info字符串的第一次出现,这是一个xml节点所以我不必愚蠢并写下所有这些switch语句......

更新

请注意我想要的所有内容都位于FileInfo节点...我希望该方法搜索我传递给它的节点!或者更好地说我想将节点本身的名称传递给此方法并获取其值。对不起,如果我在编辑之前感到困惑!

xml文件中的更多示例:

/Document/RuntimeInfo/Operator

所以我想把“操作员”传递给我的方法,我得到了它的价值!应该由方法来发现正确的路径。拍子是独一无二的,因此实施这种方法并不是一个坏主意。

4 个答案:

答案 0 :(得分:1)

不会这样做吗?

var value = ztr.SelectSingleNode(string.Format("//{0}", info).InnerText;

答案 1 :(得分:1)

return ztr.SelectSingleNode(string.Format("//Document/FileInfo/{0}", 
                            info.Replace("file", "").InnerText;

编辑

如果搜索到的节点始终处于相同的嵌套级别,则可以使用通配符

return ztr.SelectSingleNode(string.Format("//Document/*/{0}", 
                                info).InnerText;

顺便说一下,在您的示例中,您传递fileCreator以查找Creator节点。错字?

答案 2 :(得分:0)

尝试,

return ztr.SelectSingleNode(string.Format("//{0}[contains(name(..),'Info')]", info));

如果infoOperator,它将返回名称中包含Operator父节点的第一个Info节点。

答案 3 :(得分:0)

使用此XPath:

//Document/FileInfo/[0]

您的代码可以是这样的:

public string FileInfo(string info)
{
    return ztr.SelectSingleNode("//Document/FileInfo/[0]").InnerText;
}

详细了解xpath here