【问题标题】:Reading value from XML从 XML 读取值
【发布时间】:2014-03-19 05:54:30
【问题描述】:

我是 C# asp.net 编码的新手,所以我遇到了一些问题。 这是我的 xml 文件。我想检索每个员工的“”值并将它们存储在一个列表中,比如“emps_dob”。请帮我解决一下这个。谢谢你

<?xml version="1.0" encoding="utf-8"?>
<employees>
  <employee>
    <name> Vin </name>
    <DOB> 07/10 </DOB>
    <emailID> vinay@abc.com</emailID>
  </employee>
  <employee>
    <name> ben </name>
    <DOB> 08/11 </DOB>
    <emailID> ben@abc.com</emailID>
  </employee>
  <employee>
    <name> tin </name>
    <DOB> 09/12 </DOB>
    <emailID> tin@abc.com</emailID>
  </employee>

【问题讨论】:

    标签: c# xml list


    【解决方案1】:

    您可以按照post 中给出的答案使用 linq

    var doc = XDocument.Load("yourfilepath")
    var dobs= doc.Root.Elements().Select( x => x.Element("DOB") );
    


    using System;
    using System.Xml.Linq;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main( string[] args )
            {
                XDocument doc = XDocument.Load( "XMLFile1.xml" );
                List<string> emps_dob=new List<string>();
                var dobs= doc.Descendants( "DOB" );
    
                foreach ( var item in dobs)
                {
                    emps_dob.Add(item.Value);
                }
    
            }
        }
    }
    

    【讨论】:

    • 谢谢你的帮助:)
    【解决方案2】:
    XmlDocument xml = new XmlDocument();
    xml.LoadXml(myXmlString);  
    XmlNodeList xnList = xml.SelectNodes("/employees/employee");
    foreach (XmlNode xn in xnList)
    {
      string name= xn["name"].InnerText;
      string DOB= xn["name"].InnerText;
      Console.WriteLine("Name: {0} {1}", name, DOB);
    }
    

    【讨论】:

    • 谢谢你的帮助:)
    【解决方案3】:
    using System.Xml;
    
    List<string> dob = new List<string>();
    XmlDocument doc = new XmlDocument();
    doc.Load("abc.xml");
    XmlNode root = doc.DocumentElement;
    foreach (XmlNode node1 in root.ChildNodes)
    {
            foreach (XmlNode node2 in node1.ChildNodes)
            {
                   if (node2.Name.ToString() == "DOB")
                    dob.Add(node2.InnerText.ToString());
            }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-11
      • 1970-01-01
      相关资源
      最近更新 更多