简体   繁体   English

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

[英]getting specific xml data using c#

i have an xml file: 我有一个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>

I have a textbox and a button. 我有一个文本框和一个按钮。 When I type "1" and press the button my problem is how can i display the xml data to a datagridview where the value of the textbox would only show the data that has ID_num = textbox.text 当我输入“1”并按下按钮我的问题是如何将xml数据显示到datagridview,其中文本框的值只显示具有ID_num = textbox.text的数据

expected output to datagrid: 数据网格的预期输出:

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

try this: 尝试这个:

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; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM