从XML文件中读取节点

时间:2018-01-29 11:23:27

标签: .net xml vb.net

有点混淆我在这里做错了什么。我的XML

<?xml version="1.0" encoding="utf-8"?>
<customers xmlns="http://example.com/ns/" si="0" records="2">
  <customer id="123456789">
    <dob>2017-12-10T16:22:27.033Z</dob>
    <location>
      <number>444555666777</number>
    </location>
    <link rel="self" href="http://example.com" />
  </customer>
  <customer id="987654321">
    <dob>2017-12-11T17:00:00.033Z</dob>
    <location>
      <number>555666999888</number>
    </location>
    <link rel="self" href="http://example.com" />
  </customer>
  <link rel="self" href="http://example.com" />
</customers>

我正在尝试从文件中获取这两个记录(客户)以及此实例中包含的数据(最终我将其更改为LoadXml,因为XML目标来自URL但是用于测试我已复制进入文件离线工作)

所以我的代码

    Dim Xd As XmlDocument = New XmlDocument
    Xd.Load("C:\XMLFile1.xml")
    Dim Total As Integer = Xd.DocumentElement.Attributes("records").Value

    If Total > 0 Then
    Dim Customer = Xd.SelectSingleNode("/customers/customer")

客户总是什么都没有?我尝试了几种变体,包括

Xd.SelectSingleNode("/customers")
Xd.SelectSingleNode("/customer")

我尝试了Xd.DocumentElement,但我认为这也不正确。

我哪里错了?搜索谷歌和许多例子使用相同的上述?

修改

我决定将Linq视为XML,这就是我所拥有的

    Dim X As XElement = Xelement.Load("C:\XMLFile1.xml")
    Dim Total = Xelement.Attribute("records").Value
    Dim Customers As IEnumerable(Of XElement) = Xelement.Elements()

    ' Read the entire XML
    For Each c In Customers
        Console.WriteLine(c)
    Next

看起来不错,但我不知道是否还有其他我需要添加的东西,或者如果有更好的方法。

1 个答案:

答案 0 :(得分:1)

以下是将xml加载到对象中的一种方法

首先定义与xml格式匹配的对象

[XmlRoot("customers", Namespace = "http://example.com/ns/")]
public class Customers
{
    [XmlAttribute("records")]
    public int Records { get; set; }

    [XmlElement("customer")]
    public Customer[] CustomerArray;
}

public class Customer
{
    [XmlAttribute("id")]
    public int Id { get; set; }

    [XmlElement("dob")]
    public DateTime Dob { get; set; }

    [XmlElement("location")]
    public Location Location { get; set; }

    [XmlElement("link")]
    public Link Link { get; set; }
}

public class Location
{
    [XmlElement("number")]
    public long Number { get; set; }
}

public class Link
{
    [XmlAttribute("rel")]
    public string Rel { get; set; }
    [XmlAttribute("href")]
    public string HRef { get; set; }
}

然后反序列化如下

System.Xml.Serialization.XmlSerializer serializer11 = new System.Xml.Serialization.XmlSerializer(typeof(Customers));
Customers obj11 = (Customers)serializer11.Deserialize(XElement.Load(/* YOUR XML FILE PATH */).CreateReader());

希望它有所帮助。