C#中的LINQ/XML—使用XPathEvaluate返回XPATH计数
我试图理解如何从其他工具获取任何标准XPath, 让它在C#中与Linq一起工作。我知道还有很多其他方法可以得到答案,但这是为了我正在进行的具体研究和学习。C#中的LINQ/XML—使用XPathEvaluate返回XPATH计数,xml,linq,xpath-1.0,Xml,Linq,Xpath 1.0,我试图理解如何从其他工具获取任何标准XPath, 让它在C#中与Linq一起工作。我知道还有很多其他方法可以得到答案,但这是为了我正在进行的具体研究和学习。 我一直在使用XPath,似乎我应该能够使用XPath 1.0从任何其他工具复制它,并在这里运行它(就像使用XmlDocument和SelectSingleNode方法一样)。实际上,我还没有尝试使用SelectSingleNode进行计数,我将在本周末晚些时候这样做 首先,我发现我必须在XDocument上使用XPathEvaluate而不
我一直在使用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()工作,我想到了用“string(XPath)”包装XPath
有没有一种方法可以将计数返回到整数,而不必将“string()”环绕在XPath上?是的,我可以将字符串转换为整数,但为什么需要它呢 根据Microsoft文档,该方法返回的对象可以包含bool、double、string或IEnumerable,因此您可以使用
double
而不是string
来获取计数,如:
double? nullableCount = root.XPathEvaluate(xpathChildCount1) as double?;
double count = nullableCount.Value;
Console.WriteLine("ChildCount2=" + count);
结果
ChildCount2=2
我希望这对你有帮助。没必要
c#
但是XPath仍然需要string()?
ChildCount2=2
void Main()
{
XElement root = new XElement("Root",
new XElement("Child", "John"),
new XElement("Child", "Jane")
);
XDocument xdoc = new XDocument(root);
string xpathChildCount1 = "count(Root/Child)";
string strChildCount1 = xdoc.XPathEvaluate("string(" + xpathChildCount1 + ")") as string;
Console.WriteLine("ChildCount1=" + strChildCount1);
string strChildCount2 = xdoc.XPathEvaluate("count(/Root/Child)").ToString();
Console.WriteLine("ChildCount2=" + strChildCount2);
}