Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# XML文档中的搜索_C#_Xml_Winforms_Visual Studio 2008 - Fatal编程技术网

C# XML文档中的搜索

C# XML文档中的搜索,c#,xml,winforms,visual-studio-2008,C#,Xml,Winforms,Visual Studio 2008,在XML文档中搜索以根据搜索条件检索一个或多个记录的最佳方法是什么。欢迎提出建议。.net xml文档对xpath有很好的支持 它应该适用于大多数xml搜索 看看.net xml文档对xpath有很好的支持 它应该适用于大多数xml搜索 看一看如果可能的话,我个人会使用LINQtoXML。你的问题目前非常模糊,但例如,你可以写: XDocument doc = XDocument.Load("test.xml"); var matches = doc.Descendants("Person")

在XML文档中搜索以根据搜索条件检索一个或多个记录的最佳方法是什么。欢迎提出建议。

.net xml文档对xpath有很好的支持

它应该适用于大多数xml搜索


看看

.net xml文档对xpath有很好的支持

它应该适用于大多数xml搜索


看一看

如果可能的话,我个人会使用LINQtoXML。你的问题目前非常模糊,但例如,你可以写:

XDocument doc = XDocument.Load("test.xml");
var matches = doc.Descendants("Person")
                 .Where(x => (string) x.Attribute("Name") == "Jon")
                 .Where(x => x.Elements("Child").Count() >= 2);
虽然您可以使用XPath,但我通常不喜欢使用XPath—它存在着将一种语言嵌入另一种语言的所有正常问题,而使用LINQ to XML时您始终使用C#,因此您没有新语法需要学习—只有LINQ to XML库中的相关方法


LINQ to XML还使名称空间处理变得简单,您不必担心转义值等问题,因为您的查询都是以代码而不是字符串形式进行的。

如果可能的话,我个人会使用LINQ to XML。你的问题目前非常模糊,但例如,你可以写:

XDocument doc = XDocument.Load("test.xml");
var matches = doc.Descendants("Person")
                 .Where(x => (string) x.Attribute("Name") == "Jon")
                 .Where(x => x.Elements("Child").Count() >= 2);
虽然您可以使用XPath,但我通常不喜欢使用XPath—它存在着将一种语言嵌入另一种语言的所有正常问题,而使用LINQ to XML时您始终使用C#,因此您没有新语法需要学习—只有LINQ to XML库中的相关方法

LINQ to XML还使名称空间处理变得简单,您不必担心转义值等问题,因为您的查询都是以代码而不是字符串形式进行的。

使用
XPath
或选择SingleNode,如下所示:

XmlDocument doc = new XmlDocument();
doc.Load("bookstore.xml");
XmlNode root = doc.DocumentElement;

// Add the namespace.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", "urn:newbooks-schema");

// Select and display the first node in which the author's 
// last name is Kingsolver.
XmlNode node = root.SelectSingleNode(
"descendant::bk:book[bk:author/bk:last-name='Kingsolver']", nsmgr);
Console.WriteLine(node.InnerXml);
按以下方式使用
XPath
,或选择SingleNode:

XmlDocument doc = new XmlDocument();
doc.Load("bookstore.xml");
XmlNode root = doc.DocumentElement;

// Add the namespace.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("bk", "urn:newbooks-schema");

// Select and display the first node in which the author's 
// last name is Kingsolver.
XmlNode node = root.SelectSingleNode(
"descendant::bk:book[bk:author/bk:last-name='Kingsolver']", nsmgr);
Console.WriteLine(node.InnerXml);