我有一个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>
我怎样才能找到特殊的月日活动? 例如,当月份为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();
答案 0 :(得分:2)
您需要将xpath修改为以下内容:
XmlNode even= doc.SelectSingleNode("/root/Month[@index='1']/Day[@index='2']/event");
您也可以使用InnerText而不是InnerXml,因为您知道内容是文本,或您可以修改xPath以将其考虑在内:
XmlNode even = doc.SelectSingleNode("/root/Month[@index='1']/Day[@index='2']/event/text()");
string str = even.Value;
答案 1 :(得分:2)
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);
(&#39; m&#39;以及&#39; d&#39;为简单起见为字符串)