无法读取一些XML文件?

时间:2015-02-19 07:51:02

标签: c# xml linq parsing object

我尝试从Vector CANAlyzer xml文件中创建XML解析器。此代码适用于其他xml文件,但不适用于此文件。请问我在xml标准中遗漏了什么。

我想解析NetworkNodes

 XElement xmlDoc = XElement.Load(@"Short.xml");
            var result = from c in xmlDoc.Descendants("Network")
                         select new Network()
                       {
                           Network_DB_id = int.Parse(c.Attribute("DB_ID").Value),
                           Name = (string)c.Element("Name").Value,
                           ListNode = from f in c.Descendants("Node")
                                      select new Node()
                                      {
                                          Node_DB_id = int.Parse(f.Attribute("DB_ID").Value),
                                          Name = (string)f.Element("Name").Value,
                                      }
                       };
            return result.ToList();

 public class Network
    {
        public string Name { get; set; }
        public int Network_DB_id { get; set; }
        public IEnumerable<Node> ListNode { get; set; }
    }
    public class Node
    {
        public string Name { get; set; }
        public int Node_DB_id { get; set; }

        public IEnumerable<Message> ListTXMessage { get; set; }
        public IEnumerable<Message> ListRXMessage { get; set; }

    }

XML文件:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
  <Network DB_ID="-4095">
      <Name>SPACE4000</Name>
      <Attribute>
        <Name>BusType</Name>
        <Value>CAN</Value>
      </Attribute>
      <Node DB_ID="4">
        <Name>Space</Name>
        <TxMessage  DB_ID="88">
          <Name>ST_status_1</Name>
      <ID>0x520</ID>
      <Frametype>CAN Standard</Frametype>
      <DLC>8</DLC>
      <Comment></Comment>
      <Signal DB_ID="701">
        <Name>oil2</Name>
        <Bitposition>2</Bitposition>
        <Bitsize>1</Bitsize>
        <Byteorder>Intel</Byteorder>
        <Valuetype>Unsigned</Valuetype>
        <Factor>1</Factor>
        <Offset>0</Offset>
        <Minimum>0</Minimum>
        <Maximum>0</Maximum>
        <Unit></Unit>
        <Comment></Comment>
      </Signal>
    </TxMessage>
  </Node>
</Network>

1 个答案:

答案 0 :(得分:0)

没有必要像你在某些地方所做的那样投射和称呼价值(string)x.Element("foo").Valueint.Parse(x.Element("foo").Value)次调用也是如此。我编写了下面的例子,假设XML文件中可能有多个网络,但我怀疑它是否认为网络是根元素。如果只有一个网络,请考虑重构以反映这一点。

var xdoc = XDocument.Load("short.xml");

var networks = xdoc.Elements("Network").Select(x => new Network
{
    Network_DB_id = (int)x.Attribute("DB_ID"),
    Name = (string)x.Element("Name"),
    ListNode = x.Elements("Node").Select(n => new Node
    {
        Name = (string)n.Element("Name"),
        Node_DB_id = (int)n.Attribute("DB_ID"),

        // etc.
    })  
});