我试图从XML字符串中编写“文档”列表,但我想知道获取某个属性的节点值的最佳方法是什么。
更具体地说,在示例中,我想将aDocument.Source的值设置为“field”节点的文本“The Source”,该节点具有“name”属性的“Source”值。
示例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>
示例代码
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;
}
答案 0 :(得分:2)
您可以将XPath用于XmlDocument
xmlDocument.SelectSingleNode("doc/metadata/field[@name='Source']").InnerText
或者更好的是你可以使用Linq到xml和XPath
XDocument doc = XDocument.Parse(/*XML here*/);
doc.XPathSelectElement("doc/metadata/field[@name='Source']").Value