[英]find an item in xml file
i have a xml file like below 我有一个如下的xml文件
<root>
<Month name="Jan" index="1">
<Day index="2">
<event> sample 1</event>
</Day>
<Day index="3">
<event> sample 2 </event>
</Day>
</Month>
<Month name="Feb" index="2">
<Day index="5">
<event> sample 3 </event>
</Day>
<Day index="2">
<event> sample 4 </event>
</Day>
</Month>
</root>
how can i find special month and day event ? 我如何找到特殊的月份和日期事件? for example i want getting "sample 2" when month is 1 and day is 2
例如我想当月份为1且日期为2时获得“样本2”
XmlDocument doc = new XmlDocument();
doc.Load("EventsXML.xml");
XmlNode even= doc.SelectSingleNode("/root/Month[@index='1'] |/root/Month/day[@index='2']");
string str=even.InnerXml.ToString();
You need to modify your xpath to something like this: 您需要将xpath修改为以下形式:
XmlNode even= doc.SelectSingleNode("/root/Month[@index='1']/Day[@index='2']/event");
You can also use InnerText rather than InnerXml as you know the content is text, or you can modify the xPath to take this into account: 您也可以使用InnerText而不是InnerXml,因为您知道内容是文本, 或者可以修改xPath以将其考虑在内:
XmlNode even = doc.SelectSingleNode("/root/Month[@index='1']/Day[@index='2']/event/text()");
string str = even.Value;
An XDocument (Linq-to-XML) answer: XDocument(Linq-to-XML)答案:
var doc = XDocument.Load(...);
var day = doc.Root
.Descendants("Month")
.Where(e => e.Attributes("index").Value == m)
.Descendants("Day")
.Where(e => e.Attributes("index").Value == d);
('m' and 'd' as string for simplicity) (为简单起见,“ m”和“ d”为字符串)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.