我有这样的XML文件:
<ROOT>
<UNIT_VISIT>
<ID>1</ID>
<NAME>Dewi Anggraini</NAME>
<SEX>F</SEX>
<DOB>03/11/1986</DOB>
<ADDRESS>Kuningan City, Jakarta</ADDRESS>
<ID_UNIT>001</ID_UNIT>
<VISIT_DATE>03/11/2013</VISIT_DATE>
</UNIT_VISIT>
<UNIT_VISIT>
<ID>2</ID>
<NAME>Dewi Anggraini</NAME>
<SEX>F</SEX>
<DOB>03/11/1986</DOB>
<ADDRESS>Kuningan City, Jakarta</ADDRESS>
<ID_UNIT>001</ID_UNIT>
<VISIT_DATE>05/11/2013</VISIT_DATE>
</UNIT_VISIT>
</ROOT>
我想使用带有某些条件的C#来读取和过滤该xml
例如,我需要查看Name ='Dewi Anggraini'和ID_UNIT ='001'以及VISIT_DATE = '05 / 11/2013'
的位置答案 0 :(得分:2)
var elements = myXml.Element("ROOT")
.Descendants("UNIT_VISIT")
.Where(x => x.Element("NAME").Value == "Dewi Anggraini")
.Where(x => x.Element("ID_UNIT").Value == "001");
这样做了。
测试用例:
void Main()
{
String myXML = "<ROOT><UNIT_VISIT><ID>1</ID><NAME>Jack Johnson</NAME><SEX>F</SEX><DOB>03/11/1986</DOB><ADDRESS>Kuningan City, Jakarta</ADDRESS><ID_UNIT>001</ID_UNIT><VISIT_DATE>03/11/2013</VISIT_DATE></UNIT_VISIT><UNIT_VISIT><ID>2</ID><NAME>Dewi Anggraini</NAME><SEX>F</SEX><DOB>03/11/1986</DOB><ADDRESS>Kuningan City, Jakarta</ADDRESS><ID_UNIT>001</ID_UNIT><VISIT_DATE>05/11/2013</VISIT_DATE></UNIT_VISIT></ROOT>";
var doc = XDocument.Parse(myXML);
var elements = doc.Element("ROOT").Descendants("UNIT_VISIT").Where(x => x.Element("NAME").Value == "Dewi Anggraini").Where(x => x.Element("ID_UNIT").Value == "001");
Console.WriteLine (elements);
}
输出:
<UNIT_VISIT>
<ID>2</ID>
<NAME>Dewi Anggraini</NAME>
<SEX>F</SEX>
<DOB>03/11/1986</DOB>
<ADDRESS>Kuningan City, Jakarta</ADDRESS>
<ID_UNIT>001</ID_UNIT>
<VISIT_DATE>05/11/2013</VISIT_DATE>
</UNIT_VISIT>
答案 1 :(得分:0)
这应该是你要找的。永远记住,虽然你应该在提问时发布你尝试过的代码。
private void search ()
{
XmlDocument doc = new XmlDocument();
doc.Load("xml path");
XmlNode node = doc.SelectSingleNode("/Root");
string name = "Dewi Anggraini";
string id = "001";
foreach (XmlNode nodes in node.SelectNodes("UNIT_VISIT"))
{
if (nodes != null && nodes["NAME"].InnerText == name && nodes["ID_UNIT"].InnerText == id)
{
// do stuff here
}
}
}