简体   繁体   中英

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.

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:

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

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM