从XML选择节点 [英] Select node from XML
本文介绍了从XML选择节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我XML新手和litlle困惑。
I new to xml and a litlle confused.
我旁边XML
<Data>
<seo>
<Title>
<ID>Site_Title</ID>
<name>A Media</name>
</Title>
<Keywords>
<ID>Keywords</ID>
<name>A, Media, keywords</name>
</Keywords>
<Site_Description>
<ID>Site_Description</ID>
<name>A Media site description</name>
</Site_Description>
</seo>
<main_slider>
<slider1>
<id></id>
<image_url></image_url>
<text></text>
<btn_text></btn_text>
<btn_link></btn_link>
</slider1>
<slider2>
<id></id>
<image_url></image_url>
<text></text>
<btn_text></btn_text>
<btn_link></btn_link>
</slider2>
<slider3>
<id></id>
<image_url></image_url>
<text></text>
<btn_text></btn_text>
<btn_link></btn_link>
</slider3>
<slider4>
<id></id>
<image_url></image_url>
<text></text>
<btn_text></btn_text>
<btn_link></btn_link>
</slider4>
<slider5>
<id></id>
<image_url></image_url>
<text></text>
<btn_text></btn_text>
<btn_link></btn_link>
</slider5>
</main_slider>
</Data>
Masterpage.cs
XmlDocument doc = new XmlDocument();
doc.Load(Path.Combine(Request.PhysicalApplicationPath, "App_Data/A_data.xml"));
好吧,从这里我怎么能继续吗?可以说我有一个是code:
Ok, how from here i can continue? lets say i have next code:
Page.Title = title_str; // Title set
Page.MetaDescription = description; // Description set
Page.MetaKeywords = keywords; // Keywords set
我如何从XML标题>名字节点?和关键字>姓名等...
How i get the title > name node from xml? and keywords > name and so on...
必须做的只能通过的foreach?反正,怎么样?
It must done only via "foreach" ? anyway, how?
推荐答案
使用LINQ到XML:
Use Linq to Xml:
var path = Path.Combine(Request.PhysicalApplicationPath, "App_Data/A_data.xml");
XDocument xdoc = XDocument.Load(path);
var seo = xdoc.Root.Element("seo");
Page.Title = (string)seo.Element("Title").Element("name");
Page.MetaDescription = (string)seo.Element("Site_Description").Element("name");
Page.MetaKeywords = (string)seo.Element("Keywords").Element("name");
// etc
此外,我建议你采取 LINQ看看到XML的样品了解如何在将来使用它。
Also I suggest you to take a look on LINQ to XML Samples to understand how to use it in future.
您还可以使用XPath(这是更好的选择,如果一些元素的一些可能会丢失):
You can also use xpath (it's better option, if some some element could be missing):
Page.Title = (string)xdoc.XPathSelectElement("Data/seo/Title/name");
这篇关于从XML选择节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文