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

标签 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>

我有一个文本框和一个按钮。当我键入“1”并按下按钮时,我的问题是如何将 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

最佳答案

试试这个:

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

关于c# - 使用c#获取特定的xml数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40523316/

相关文章:

c# - 在 datagridview 的工具提示中显示图像

javascript - 如何为网格中的字段调用 javascript 函数

c# - 如何以 Web.Config 中的本地化格式显示 DateTime 的字符串

c# - 为什么会出现 Invalid Expression Term "String"?

c# - Microsoft分析器为什么找不到Microsoft.CodeAnalysis?

c# - Linq To Twitter 清除 IOAuthCredentials 凭据

javascript - 如何获取 HTML 元素的字符串表示形式

xml - 如何从大型 XML 文档中获取流式迭代器 [Node]?

c# - 如何使用绑定(bind)源更新数据 GridView

java - 从 xml 中删除终止符号