[英]Using C# to Query XML where multiple child element have the same name
I have created an XML file of Documents with multiple meta data tags. 我创建了带有多个元数据标签的Documents XML文件。
Its looks something like this: 它看起来像这样:
<?xml version="1.0" encoding="utf-8" ?>
<documents>
<document>
<name>Document 1</name>
<tag>Tag 1</tag>
<tag>tag 2</tag>
<tag>Tag 3 </tag>
<tag>Tag 4</tag>
</document>
<document>
<name>Document 2</name>
<tag>Tag 1</tag>
<tag>Tag 4</tag>
<tag>Tag 5</tag>
<tag>Tag 6</tag>
</document>
<document>
<name>Document 3</name>
<tag>Tag 3</tag>
<tag>Tag 4</tag>
<tag>Tag 5</tag>
<tag>Tag 7</tag>
</document>
</documents>
I want a user to be able to input a search term (one of the tags) and have it return the name of all documents that have the tag. 我希望用户能够输入搜索词(标签之一)并使它返回所有带有标签的文档的名称。
Currently I am using the following code to query my XML: 当前,我正在使用以下代码查询我的XML:
String str = "";
var search = searchBox3.Text;
var title = "";
var xmlMetaFilePath = Server.MapPath("XML/MetaDataTest.xml");
DataSet dsMetaDetails = new DataSet();
dsMetaDetails.ReadXml(xmlMetaFilePath);// Load XML in dataset
DataTable updates = dsMetaDetails.Tables[0];
EnumerableRowCollection<DataRow> updateQuery =
from update in updates.AsEnumerable()
where update.Field<string>("tag") == search
select update;
DataView updateView = updateQuery.AsDataView();
if (updateView.Count > 0)
{
foreach (DataRow row in updateQuery)
{
title = row.Field<string>("name");
answer.Text = title;
str = str + title;
}
answer.Text = str;
}
else
{
answer.Text = "None";
}
But, this does not return values for child elements where multiple child elements have the same name. 但是,这不会返回多个子元素具有相同名称的子元素的值。 Any idea on how to check query against all child elements with the same name?
关于如何检查具有相同名称的所有子元素的查询的任何想法吗?
Use LINQ to Xml 使用LINQ转换为Xml
string searchTag = "some tag";
XDocument file = XDocument.Load("filepath.xml");
var documents = file.Root
.Elements("document")
.Where(doc => doc.Elements("tag")
.Any(tag => tag.Value.Equals(searchTag));
foreach(var doc in documents)
{
string docName = doc.Element("name").Value;
Console.WriteLine(docName);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.