【发布时间】:2020-06-12 21:41:40
【问题描述】:
我正在尝试了解如何从另一个工具中获取任何标准 XPath,
并使其在 C# 中与 Linq 一起工作。我知道还有很多其他方法可以得到答案,但这是针对我正在做的特定研究和学习。
我一直在使用 XPath,似乎我应该能够使用 XPath 1.0 从任何其他工具复制它并在此处运行它(就像我可以使用 XmlDocument 和 SelectSingleNode 方法一样)。实际上,我还没有尝试使用 SelectSingleNode 进行计数,将在本周末晚些时候进行。
首先,我发现我必须在 XDocument 上使用 XPathEvaluate 而不是 XElement,因此我不必删除 XPath 的第一部分。
using System;
using System.Xml.Linq;
using System.Xml.XPath;
namespace Linq_Test
{
class Program
{
static void Main(string[] args)
{
XElement root = new XElement("Root",
new XElement("Child", "John"),
new XElement("Child", "Jane")
);
XDocument xdoc = new XDocument(root);
/*
XElement el = root.XPathSelectElement("./Child[1]");
Console.WriteLine(el);
*/
string xpathChildCount1 = "count(Root/Child)";
string strChildCount1 =
xdoc.XPathEvaluate("string(" + xpathChildCount1 + ")") as string;
Console.WriteLine("ChildCount1=" + strChildCount1);
string strChildCount2 =
xdoc.XPathEvaluate(xpathChildCount1) as string;
Console.WriteLine("ChildCount2=" + strChildCount2);
/*
int intChildCount = (int)root.XPathEvaluate("string(" + xpathChildCount + ")");
Console.WriteLine("Numeric ChildCount=" + intChildCount);
*/
Console.WriteLine("\n\n Press enter to end ....");
Console.ReadLine();
}
}
}
为了让 Count() 工作,this StackOverflow post 给了我用“string(XPath)”包装 XPath 的想法。
ChildCount1=2
ChildCount2=
有没有一种方法可以将计数恢复为整数,而不必在 XPath 周围包裹“string()”?是的,我可以将字符串转换为整数,但为什么需要它?
【问题讨论】: