使用c#获取特定的xml数据

时间:2016-11-10 08:48:04

标签: c# xml datagridview

我有一个xml文件:

<Address>
  <Data2>
    <Person>
      <EMPL_NUM>>100</EMPL_NUM>
      <NAME>Carl</NAME>
      <ID_NUM>1</ID_NUM>
      <IsRequired>0</IsRequired>
    </Person>
    <Person>
      <EMPL_NUM>200</EMPL_NUM>
      <NAME>Mark</NAME>
      <ID_NUM>2</ID_NUM>
      <IsRequired>0</IsRequired>
    </Person>
    <Person>
      <EMPL_NUM>300</EMPL_NUM>
      <NAME>Tanner</NAME>
      <ID_NUM>3</ID_NUM>
      <IsRequired>0</IsRequired>
    </Person>
 </Data2>
</Address>

我有一个文本框和一个按钮。当我输入&#34; 1&#34;并按下按钮我的问题是如何将xml数据显示到datagridview,其中文本框的值只显示具有ID_num = textbox.text的数据

数据网格的预期输出:

if txtbox1.text = 1:

 EMPL_NUM  |  Name  |  ID_NUM  |  IsRequired                  
   100     |  Carl  |    1     |      0

if txtbox1.text = 3:

 EMPL_NUM  |  Name  |  ID_NUM  |  IsRequired                  
   300     | Tanner |    3     |      0

1 个答案:

答案 0 :(得分:3)

试试这个:

class Program
{
    static void Main(string[] args)
    {
        // read your xml from somewhere
        var xml = File.ReadAllText("Address.xml");
        XDocument xmldoc = XDocument.Parse(xml);

        // get the element by id
        var element = GetElementById(xmldoc, 1);

        // deserialize element
        var xmlSerializer = new XmlSerializer(typeof(Person));
        var person = (Person)xmlSerializer.Deserialize(element.CreateReader());

        // continue to work with person
    }

    private static XElement GetElementById(XDocument xmldoc, string id)
    {
        // Elements according to your XML file
        var element = xmldoc.Element("Address")
            .Elements("Data2")
            .Elements("Person")
            .Single(x => x.Element("ID_NUM").Value == id);
        return element;
    }
}


/// <summary>
/// Used for deserialization
/// </summary>
public class Person
{
    public int EMPL_NUM { get; set; }
    public string NAME { get; set; }
    public int ID_NUM { get; set; }
    public bool IsRequired { get; set; }
}