0

我有这样的 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' and ID_UNIT='001' and VISIT_DATE='05/11/2013'

4

2 回答 2

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>
于 2013-11-03T16:32:48.863 回答
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
            }
        }
    }
于 2013-11-03T16:32:39.730 回答