使用 Xdocument 读取具有特定属性的节点的值
我试图从 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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 XPath to XmlDocument
或者更好,您可以使用 Linq to xml 和 XPath
You can use XPath to XmlDocument
Or better you can use Linq to xml, and XPath