如何从xml文件中获取嵌套元素

Posted

技术标签:

【中文标题】如何从xml文件中获取嵌套元素【英文标题】:How to get nested element from xml file 【发布时间】:2021-10-21 00:53:05 【问题描述】:

我尝试在 XML 文件中返回一些嵌套值。我想为每张桌子返回邮政编码的值、重量和值。

所以我有这个 xml 文件:

<?xml version="1.0"?>
<Container xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Id>684</Id>
  <dateCool>2011-08-22T00:00:00+05:00</dateCool>
  <desks>
    <desk>
      <Sender>
        <Name>Jan</Name>
        <Address>
          <Street>bood</Street>
          <HouseNumber>22</HouseNumber>
          <PostalCode>2402AE</PostalCode>
          <City>Al Rijn</City>
        </Address>
      </Sender>
      <participant>
        <Name>Piet</Name>
        <Address>
          <Street>Schan</Street>
          <HouseNumber>22</HouseNumber>
          <PostalCode>2497AV</PostalCode>
          <City>Den Haag</City>
        </Address>
      </participant>
      <Weight>0.02</Weight>
      <Value>0.0</Value>
    </desk>
    <desk>
      <Sender xsi:type="Company">
        <Name>ykken groot B.V.</Name>
        <Address>
          <Street>ILSY-PLantsoen</Street>
          <HouseNumber>1</HouseNumber>
          <PostalCode>2497GA</PostalCode>
          <City>Den Haag</City>
        </Address>
        <CcNumber>65465424</CcNumber>
      </Sender>
      <participant>
        <Name>Aad</Name>
        <Address>
          <Street>Korenbloemkamp</Street>
          <HouseNumber>22</HouseNumber>
          <PostalCode>2353HS</PostalCode>
          <City>Leiderdorp</City>
        </Address>
      </participant>
      <Weight>2.0</Weight>
      <Value>0.0</Value>
    </desk>
    <desk>
      <Sender xsi:type="Company">
        <Name>seti</Name>
        <Address>
          <Street>ILSY-PLantsoen</Street>
          <HouseNumber>1</HouseNumber>
          <PostalCode>2497GA</PostalCode>
          <City>Den Haag</City>
        </Address>
        <CcNumber>65465424</CcNumber>
      </Sender>
      <participant>
        <Name>Martijn</Name>
        <Address>
          <Street>Burgemeester Roosstraat</Street>
          <HouseNumber>33</HouseNumber>
          <PostalCode>3035 AC</PostalCode>
          <City>Rotterdam</City>
        </Address>
      </participant>
      <Weight>100.0</Weight>
      <Value>2000.0</Value>
    </desk>
    <desk>
      <Sender xsi:type="Company">
        <Name>Aad</Name>
        <Address>
          <Street>Korenbloemkamp</Street>
          <HouseNumber>22</HouseNumber>
          <PostalCode>2353HS</PostalCode>
          <City>Leiderdorp</City>
        </Address>
      </Sender>
      <participant>
        <Name>Martijn</Name>
        <Address>
          <Street>Burge Roosaat</Street>
          <HouseNumber>33</HouseNumber>
          <PostalCode>3035 AC</PostalCode>
          <City>Rotterdam</City>
        </Address>
      </participant>
      <Weight>11</Weight>
      <Value>500</Value>
    </desk>
  </desks>
</Container>

我的代码如下所示:

static void Main(string[] args)
        
            FileStream fs = new FileStream("Container.xml", FileMode.Open);
            StreamReader sr = new StreamReader(fs);

            string s = sr.ReadToEnd();

            sr.Close();
            fs.Close();

            List<Dictionary<string, string>> orderList = new List<Dictionary<string, string>>();
            XDocument xDocument = XDocument.Parse(s);

            //Get all nodes
            List<XNode> xNodes = xDocument.DescendantNodes().ToList();
            foreach (XNode node in xNodes)
            
                XElement element = node as XElement;
                if (element.Name != "desk") continue;
                Dictionary<string, string> dict = new Dictionary<string, string>();

                //For each orderProperty, get all attributes
                foreach (XAttribute attribute in element.Attributes())
                
                    dict.Add(attribute.Name.ToString(), attribute.Value);
                
                orderList.Add(dict);
            


            foreach (Dictionary<string, string> dict in orderList)
            
                foreach (string key in dict.Keys)
                
                    Console.Write(key + ": " + dict[key] + ", ");
                
                Console.Write("\n");
            

        

但我每次都会收到这个错误:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

【问题讨论】:

【参考方案1】:

因为有些xnodes是空的

使用此代码

它有效:)

static void Main(string[] args)

        var s = string.Empty;

        using (var fs = new FileStream("Container.xml", FileMode.Open))
        
            using (var sr = new StreamReader(fs))
            
                s = sr.ReadToEnd();
            
        

        var orderList = new List<Dictionary<string, string>>();
        var xDocument = XDocument.Parse(s);


        var xNodes = xDocument.DescendantNodes().ToList();
        foreach (var node in xNodes)
        
            var element = node as XElement;
            if (element == null) continue;
            if (element.Name != "desk") continue;
            var dict = new Dictionary<string, string>();


            foreach (var deskNode in element.Nodes())
            
                var deskElement = deskNode as XElement;
                if (deskElement == null) continue;

                dict.Add(deskElement.Name.ToString(), deskElement.Value);
            
            orderList.Add(dict);
        


        foreach (var dict in orderList)
        
            foreach (string key in dict.Keys)
            
                Console.Write(key + ": " + dict[key] + ", ");

            
            Console.Write("\n");
        

        Console.ReadKey();
 

我改变了你的第二个 foreach 循环 element.Attributes() return null

【讨论】:

以上是关于如何从xml文件中获取嵌套元素的主要内容,如果未能解决你的问题,请参考以下文章

如何使用python修改xml文件中嵌套元素的文本?

如何从元素中具有相同名称的 xml 文件中获取特定值?

如何从结构类似于Java的XML文件中获取特定元素

如何在具有 xmlns 属性的 xml 中使用 xpath 获取特定的嵌套元素? [复制]

XML解析器(Unmarshal)使用JaxB从xml文件中获取元素

如何使用 C# ASP.Net 从 XML 文档中获取特定 XML 元素的列表?