1

Im trying to write a List of 'Documents' from an XML string, but i was wondering what is the best way to get the value of a node of certain attribute.

More specifically in the sample I would like to set the value of aDocument.Source to the text "The Source" of the "field" node that has the "Source" value for the "name" attribute.

Sample XML:

<doc>
      <docitem>3</docitem>
      <docid>129793</docid>
      <doctitle>Some Title</doctitle>
      <docdate>2009-07-03</docdate>
      <metadata>
        <field name="Date">2009-07-03 14:45:00</field>
        <field name="SourceArea">The Source Area</field>
        <field name="Source">The Source</field>
        <field name="Organisation">Some Organisation</field>
      </metadata>
      <summary>
        <summarytext>Some Summary</summarytext>
      </summary>
    </doc>

Sample Code

  protected override List<Document> GetDocuments(string xmlString)
        {
            //Parse the string
            XDocument xDocument = XDocument.Parse(xmlString);

            //Create a List of Document objects, from the doc xml element.
            List<Document> documents = (from doc in xDocument.Descendants("doc")
                                        select new Document
                                        {
                                            DocId = Convert.ToInt32(doc.Element("docid").Value),
                                            DocTitle = doc.Element("doctitle").Value,
                                            DocDateTime = DateTime.Parse(doc.Element("docdate").Value),
                                            DocSummary = doc.Element("summary").Value,
                                            DocBody = "",
                                            DocUrl = doc.Element("docid").Value,
                                            Source = "" //CODE NEEDED
                                        }
                                        ).ToList<Document>();



            return documents;

        }

1 Answer 1

2

You can use XPath to XmlDocument

 xmlDocument.SelectSingleNode("doc/metadata/field[@name='Source']").InnerText

Or better you can use Linq to xml, and XPath

XDocument doc = XDocument.Parse(/*XML here*/);
doc.XPathSelectElement("doc/metadata/field[@name='Source']").Value
Sign up to request clarification or add additional context in comments.

2 Comments

I dont seem to find the SelectSingleNode or XPathSelectElement methods in Linq.XElement or Linq.XDocument.
I was missing the System.Xml.XPath namespace. doc.XPathSelectElement("./metadata/field[@name='SOURCE']").Value works.

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.