0

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?

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.