0
<?xml version="1.0" encoding="utf-8" ?>
<class name="EmployeeData.Employee">
  <property emp="1">
    <empid>12345678</empid>
    <empname>ABC1</empname>
    <project>XYZ1</project>
  </property>
  <property emp="2">
    <empid>87654321</empid>
    <empname>ABC2</empname>
    <project>XYZ2</project>
  </property>
</class>

在上面的 XML 文档中,我有两个按名称命名的节点property。我需要解析它并存储值:"12345678","ABC1","XYZ1"在一个对象和"87654321","ABC2","XYZ2"另一个对象中。此外,我应该能够在以后随时随地使用这两个对象。我怎样才能做到这一点?

4

2 回答 2

1

Use LINQ2XML

var doc=XDocument.Load(url);
var output= doc.Elements("property").Select(x=>
              new
              {
                    empid=x.Element("empid").Value,
                    empname=x.Element("empname").Value,
                    project=x.Element("project").Value
              }
);

Now you can iterate over output

foreach(var property in output)
{
    property.empid;
    property.empname;
    property.project;
}
于 2013-09-17T04:23:10.553 回答
0

首先获取每个 <property>

XmlDocument xdoctest = new XmlDocument();    
xdoctest.LoadXml("...");   
XmlNodeList nodes = xdoctest.SelectNodes("class/property");

然后遍历每个属性节点,遍历该节点的每个元素并获取值。在此示例中,我附加到 StringBuilder ,但对其进行编辑以满足您的需要。

foreach (XmlNode node in nodes)
{
    StringBuilder nodeString = new StringBuilder();
    foreach(XmlElement elm in node)
    {
        nodeString.Append(elm.InnerText + ",");
    }
    // Remove last ,
    nodeString = new StringBuilder(nodeString.ToString().Substring(0, nodeString.Length - 1));
    Console.WriteLine(nodeString);
}

根据您提供的 XML,输出为:

12345678,ABC1,XYZ1
87654321,ABC2,XYZ2
于 2013-09-17T04:36:35.750 回答