pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

<legend id='WPefi'><style id='WPefi'><dir id='WPefi'><q id='WPefi'></q></dir></style></legend>

<small id='WPefi'></small><noframes id='WPefi'>

  • <i id='WPefi'><tr id='WPefi'><dt id='WPefi'><q id='WPefi'><span id='WPefi'><b id='WPefi'><form id='WPefi'><ins id='WPefi'></ins><ul id='WPefi'></ul><sub id='WPefi'></sub></form><legend id='WPefi'></legend><bdo id='WPefi'><pre id='WPefi'><center id='WPefi'></center></pre></bdo></b><th id='WPefi'></th></span></q></dt></tr></i><div class="aiyo2k2" id='WPefi'><tfoot id='WPefi'></tfoot><dl id='WPefi'><fieldset id='WPefi'></fieldset></dl></div>
    <tfoot id='WPefi'></tfoot>
        <bdo id='WPefi'></bdo><ul id='WPefi'></ul>

        如何使用 XmlSerializer 反序列化大型文檔中的節點

        How to deserialize a node in a large document using XmlSerializer(如何使用 XmlSerializer 反序列化大型文檔中的節點)
      1. <tfoot id='4tADb'></tfoot>

          <bdo id='4tADb'></bdo><ul id='4tADb'></ul>

              <i id='4tADb'><tr id='4tADb'><dt id='4tADb'><q id='4tADb'><span id='4tADb'><b id='4tADb'><form id='4tADb'><ins id='4tADb'></ins><ul id='4tADb'></ul><sub id='4tADb'></sub></form><legend id='4tADb'></legend><bdo id='4tADb'><pre id='4tADb'><center id='4tADb'></center></pre></bdo></b><th id='4tADb'></th></span></q></dt></tr></i><div class="a20aac0" id='4tADb'><tfoot id='4tADb'></tfoot><dl id='4tADb'><fieldset id='4tADb'></fieldset></dl></div>
                  <tbody id='4tADb'></tbody>
                1. <legend id='4tADb'><style id='4tADb'><dir id='4tADb'><q id='4tADb'></q></dir></style></legend>

                  <small id='4tADb'></small><noframes id='4tADb'>

                2. 本文介紹了如何使用 XmlSerializer 反序列化大型文檔中的節點的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

                  問題描述

                  限時送ChatGPT賬號..

                  我有一個大型 XML 文檔,已加載到 XmlDocument 中,我想使用 XmlSerializer 類將其中的選定元素反序列化為生成的 .NET 類使用 xsd.exe.

                  I have a large XML document that I have loaded into an XmlDocument and I want to use the XmlSerializer class to deserialize selected elements from it into a .NET class generated using xsd.exe.

                  這是迄今為止我嘗試過的 MCVE;xsd 和生成的類在帖子的末尾.如代碼中的注釋中所述,我得到一個 InvalidOperationException - <Cars xmlns:'http://MyNamespace'/>沒想到:

                  Here's an MCVE of what I've tried so far; the xsd and generated class are at the end of the post. As noted in the comments in the code, I am getting an InvalidOperationException - <Cars xmlns:'http://MyNamespace' /> was not expected:

                  static string XmlContent = @"
                      <RootNode xmlns=""http://MyNamespace"">
                          <Cars>
                          <Car make=""Volkswagen"" />
                          <Car make=""Ford"" />
                          <Car make=""Opel"" />
                          </Cars>
                      </RootNode>";
                  
                  static void TestMcve()
                  {
                      var doc = new XmlDocument();
                      doc.LoadXml(XmlContent);
                      var nsMgr = new XmlNamespaceManager(doc.NameTable);
                      nsMgr.AddNamespace("myns", "http://MyNamespace");
                      var rootSerializer = new XmlSerializer(typeof(RootNode));
                      var root = (RootNode) rootSerializer.Deserialize(new XmlNodeReader(doc));
                      Console.WriteLine(root.Cars[0].make); // Works fine so far
                  
                      var node = doc.DocumentElement.SelectSingleNode("myns:Cars", nsMgr);
                      Console.WriteLine(node.OuterXml);
                      var carSerializer = new XmlSerializer(typeof(Car));
                      using (var reader = new XmlNodeReader(node))
                      {
                          // What I want is a list of Car instances deserialized from
                          // the Car child elements of the Cars element.
                          // The following line throws an InvalidOperationException
                          // "<Cars xmlns:'http://MyNamespace' /> was not expected"
                          // If I change SelectSingleNode above to select "myns:Cars/myns:Car"
                          // I get "<Car xmlns:'http://MyNamespace' /> was not expected"
                          var result = carSerializer.Deserialize(reader);
                      }
                  }
                  

                  我還想隨后更新我的 Car 類實例,并使用 XmlSerializer 將其插入回文檔中,這是后續問題的主題 如何使用 XmlSerializer 在大文檔中插入節點.

                  I also want to subsequently update my Car class instance, and insert it back into the document using the XmlSerializer, which is the subject of a follow-up question How to insert a node in a large document using XmlSerializer .

                  xsd 和生成的類如下:

                  The xsd and generated classes follow:

                  <xs:schema xmlns="http://MyNamespace" xmlns:xs="http://www.w3.org/2001/XMLSchema" 
                             targetNamespace="http://MyNamespace" 
                             elementFormDefault="qualified" attributeFormDefault="unqualified" 
                             version="3.9.0.8">
                    <xs:complexType name="Cars">
                      <xs:sequence>
                        <xs:element name="Car" type="Car" maxOccurs="unbounded"/>
                      </xs:sequence>
                    </xs:complexType>
                    <xs:complexType name="Car">
                      <xs:attribute name="make" type="xs:string" use="required"/>
                    </xs:complexType>
                    <xs:complexType name="RootNode">
                      <xs:sequence>
                        <xs:element name="Cars" type="Cars" minOccurs="0"/>
                      </xs:sequence>
                    </xs:complexType>
                    <xs:element name="RootNode" type="RootNode" />
                  </xs:schema>
                  

                  xsd.exe 生成的代碼:

                  Code generated by xsd.exe:

                  using System.Xml.Serialization;
                  
                  
                  /// <remarks/>
                  [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
                  [System.SerializableAttribute()]
                  [System.Diagnostics.DebuggerStepThroughAttribute()]
                  [System.ComponentModel.DesignerCategoryAttribute("code")]
                  [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://MyNamespace")]
                  [System.Xml.Serialization.XmlRootAttribute(Namespace="http://MyNamespace", IsNullable=false)]
                  public partial class RootNode {
                  
                      private Car[] carsField;
                  
                      /// <remarks/>
                      [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable=false)]
                      public Car[] Cars {
                          get {
                              return this.carsField;
                          }
                          set {
                              this.carsField = value;
                          }
                      }
                  }
                  
                  /// <remarks/>
                  [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.1055.0")]
                  [System.SerializableAttribute()]
                  [System.Diagnostics.DebuggerStepThroughAttribute()]
                  [System.ComponentModel.DesignerCategoryAttribute("code")]
                  [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://MyNamespace")]
                  public partial class Car {
                  
                      private string makeField;
                  
                      /// <remarks/>
                      [System.Xml.Serialization.XmlAttributeAttribute()]
                      public string make {
                          get {
                              return this.makeField;
                          }
                          set {
                              this.makeField = value;
                          }
                      }
                  }
                  

                  推薦答案

                  這里有兩個問題:

                  1. var node = doc.DocumentElement.SelectSingleNode("myns:Cars", nsMgr); 位于 元素——<Car> 節點的重復序列的容器元素 - 但您的 XmlSerializer 被構造為反序列化名為 <Car>.嘗試使用反序列化單個汽車的序列化程序反序列化一系列汽車是行不通的.

                  1. The var node = doc.DocumentElement.SelectSingleNode("myns:Cars", nsMgr); is positioned at the <Cars> element -- the container element for the repeating sequence of <Car> nodes -- but your XmlSerializer is constructed to deserialize a single root element named <Car>. Trying to deserialize a sequence of cars with a serializer constructed to deserialize a single car will not work.

                  出于某種原因,xsd.exe 為您的 Car 類型生成了一個定義,但沒有 XmlRoot 屬性:

                  For some reason xsd.exe generated a definition for your Car type without an XmlRoot attribute:

                  [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://MyNamespace")]
                  // Not included!
                  //[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://MyNamespace")]
                  public partial class Car
                  {
                  }
                  

                  因此,如果您嘗試將 Car 作為 XML 文檔的根 XML 元素序列化或反序列化,那么 XmlSerializer 將期望該根元素不在任何命名空間中.大型文檔中的每個 <Car> 節點都位于 "http://MyNamespace" 默認命名空間中,因此嘗試單獨反序列化每個節點也行不通.

                  Thus if you attempt to serialize or deserialize a single instance of a Car as the root XML element of an XML document then XmlSerializer will expect that root element to not be in any namespace. Each <Car> node in your large document is in the "http://MyNamespace" default namespace, so attempting to deserialize each one individually also will not work.

                  您可以手動將缺少的 [XmlRoot(Namespace = "http://MyNamespace")] 屬性添加到 Car,但這樣做可能會很麻煩如果隨后修改了 XSD 文件并且需要重新生成 c# 類型.

                  You could manually add the missing [XmlRoot(Namespace = "http://MyNamespace")] attribute to Car, but having to do this can be a nuisance if the XSD files are subsequently modified and the c# types need to be regenerated.

                  要避免這兩個問題,您可以使用 XmlNode.SelectNodes(String, XmlNamespaceManager) 選擇 元素內的每個 節點,然后通過 構造一個帶有重寫 XmlRootAttribute 的 XmlSerializer 帶有被反序列化的節點的元素名稱和命名空間.首先,定義如下擴展方法:

                  To avoid both issues, you can use XmlNode.SelectNodes(String,?XmlNamespaceManager) to select every <Car> nodes inside the <Cars> element, then deserialize each one by constructing an XmlSerializer with an override XmlRootAttribute with the element name and namespace of the node being deserialized. First, define the following extension methods:

                  public static partial class XmlNodeExtensions
                  {
                      public static List<T> DeserializeList<T>(this XmlNodeList nodes)
                      {
                          return nodes.Cast<XmlNode>().Select(n => n.Deserialize<T>()).ToList();
                      }
                  
                      public static T Deserialize<T>(this XmlNode node)
                      {
                          if (node == null)
                              return default(T);
                          var serializer = XmlSerializerFactory.Create(typeof(T), node.LocalName, node.NamespaceURI);
                          using (var reader = new XmlNodeReader(node))
                          {
                              return (T)serializer.Deserialize(reader);
                          }
                      }
                  }
                  
                  public static class XmlSerializerFactory
                  {
                      // To avoid a memory leak the serializer must be cached.
                      // https://stackoverflow.com/questions/23897145/memory-leak-using-streamreader-and-xmlserializer
                      // This factory taken from 
                      // https://stackoverflow.com/questions/34128757/wrap-properties-with-cdata-section-xml-serialization-c-sharp/34138648#34138648
                  
                      readonly static Dictionary<Tuple<Type, string, string>, XmlSerializer> cache;
                      readonly static object padlock;
                  
                      static XmlSerializerFactory()
                      {
                          padlock = new object();
                          cache = new Dictionary<Tuple<Type, string, string>, XmlSerializer>();
                      }
                  
                      public static XmlSerializer Create(Type serializedType, string rootName, string rootNamespace)
                      {
                          if (serializedType == null)
                              throw new ArgumentNullException();
                          if (rootName == null && rootNamespace == null)
                              return new XmlSerializer(serializedType);
                          lock (padlock)
                          {
                              XmlSerializer serializer;
                              var key = Tuple.Create(serializedType, rootName, rootNamespace);
                              if (!cache.TryGetValue(key, out serializer))
                                  cache[key] = serializer = new XmlSerializer(serializedType, new XmlRootAttribute { ElementName = rootName, Namespace = rootNamespace });
                              return serializer;
                          }
                      }
                  }
                  

                  然后反序列化如下:

                  var nodes = doc.DocumentElement.SelectNodes("myns:Cars/myns:Car", nsMgr);
                  var cars = nodes.DeserializeList<Car>();
                  

                  如此答案 Marc Gravell.

                  示例工作 .Net fiddle.

                  這篇關于如何使用 XmlSerializer 反序列化大型文檔中的節點的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

                  【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

                  相關文檔推薦

                  What are good algorithms for vehicle license plate detection?(車牌檢測有哪些好的算法?)
                  onClick event for Image in Unity(Unity中圖像的onClick事件)
                  Running Total C#(運行總 C#)
                  Deleting a directory when clicked on a hyperlink with JAvascript.ASP.NET C#(單擊帶有 JAvascript.ASP.NET C# 的超鏈接時刪除目錄)
                  asp.net listview highlight row on click(asp.net listview 在單擊時突出顯示行)
                  Calling A Button OnClick from a function(從函數調用按鈕 OnClick)
                    <tbody id='tCdAF'></tbody>
                    1. <tfoot id='tCdAF'></tfoot><legend id='tCdAF'><style id='tCdAF'><dir id='tCdAF'><q id='tCdAF'></q></dir></style></legend>
                        <bdo id='tCdAF'></bdo><ul id='tCdAF'></ul>

                        1. <small id='tCdAF'></small><noframes id='tCdAF'>

                          • <i id='tCdAF'><tr id='tCdAF'><dt id='tCdAF'><q id='tCdAF'><span id='tCdAF'><b id='tCdAF'><form id='tCdAF'><ins id='tCdAF'></ins><ul id='tCdAF'></ul><sub id='tCdAF'></sub></form><legend id='tCdAF'></legend><bdo id='tCdAF'><pre id='tCdAF'><center id='tCdAF'></center></pre></bdo></b><th id='tCdAF'></th></span></q></dt></tr></i><div class="ciiywi0" id='tCdAF'><tfoot id='tCdAF'></tfoot><dl id='tCdAF'><fieldset id='tCdAF'></fieldset></dl></div>

                          • 主站蜘蛛池模板: 山东彩钢板房,山东彩钢活动房,临沂彩钢房-临沂市贵通钢结构工程有限公司 | 理化生实验室设备,吊装实验室设备,顶装实验室设备,实验室成套设备厂家,校园功能室设备,智慧书法教室方案 - 东莞市惠森教学设备有限公司 | 空冷器|空气冷却器|空水冷却器-无锡赛迪森机械有限公司[官网] | 箱式破碎机_移动方箱式破碎机/价格/厂家_【华盛铭重工】 | LNG鹤管_内浮盘价格,上装鹤管,装车撬厂家-连云港赛威特机械 | 包塑丝_高铁绑丝_地暖绑丝_涂塑丝_塑料皮铁丝_河北创筹金属丝网制品有限公司 | 兰州牛肉面加盟,兰州牛肉拉面加盟-京穆兰牛肉面 | 阻垢剂,反渗透阻垢剂,缓蚀阻垢剂-山东普尼奥水处理科技有限公司 真空粉体取样阀,电动楔式闸阀,电动针型阀-耐苛尔(上海)自动化仪表有限公司 | 驾驶人在线_专业学车门户网站| 北京环球北美考试院【官方网站】|北京托福培训班|北京托福培训 | 山东太阳能路灯厂家-庭院灯生产厂家-济南晟启灯饰有限公司 | 细沙回收机-尾矿干排脱水筛设备-泥石分离机-建筑垃圾分拣机厂家-青州冠诚重工机械有限公司 | 软文推广发布平台_新闻稿件自助发布_媒体邀约-澜媒宝 | 根系分析仪,大米外观品质检测仪,考种仪,藻类鉴定计数仪,叶面积仪,菌落计数仪,抑菌圈测量仪,抗生素效价测定仪,植物表型仪,冠层分析仪-杭州万深检测仪器网 | 河南中整光饰机械有限公司-抛光机,去毛刺抛光机,精密镜面抛光机,全自动抛光机械设备 | 品牌设计_VI设计_电影海报设计_包装设计_LOGO设计-Bacross新越品牌顾问 | 中国在职研究生招生信息网| 微型驱动系统解决方案-深圳市兆威机电股份有限公司 | 玻璃瓶厂家_酱菜瓶厂家_饮料瓶厂家_酒瓶厂家_玻璃杯厂家_徐州东明玻璃制品有限公司 | 防腐木批发价格_深圳_惠州_东莞防腐木厂家_森源(深圳)防腐木有限公司 | 广东恩亿梯电源有限公司【官网】_UPS不间断电源|EPS应急电源|模块化机房|电动汽车充电桩_UPS电源厂家(恩亿梯UPS电源,UPS不间断电源,不间断电源UPS) | 沈阳缠绕包装机厂家直销-沈阳海鹞托盘缠绕包装机价格 | 耐力板-PC阳光板-PC板-PC耐力板 - 嘉兴赢创实业有限公司 | 电脑刺绣_绣花厂家_绣花章仔_织唛厂家-[源欣刺绣]潮牌刺绣打版定制绣花加工厂家 | 【同风运车官网】一站式汽车托运服务平台,验车满意再付款 | 【ph计】|在线ph计|工业ph计|ph计厂家|ph计价格|酸度计生产厂家_武汉吉尔德科技有限公司 | 杭州顺源过滤机械有限公司官网-压滤机_板框压滤机_厢式隔膜压滤机厂家 | 铁艺,仿竹,竹节,护栏,围栏,篱笆,栅栏,栏杆,护栏网,网围栏,厂家 - 河北稳重金属丝网制品有限公司 山东太阳能路灯厂家-庭院灯生产厂家-济南晟启灯饰有限公司 | 医疗仪器模块 健康一体机 多参数监护仪 智慧医疗仪器方案定制 血氧监护 心电监护 -朗锐慧康 | 对辊式破碎机-对辊制砂机-双辊-双齿辊破碎机-巩义市裕顺机械制造有限公司 | 伸缩器_伸缩接头_传力接头-巩义市润达管道设备制造有限公司 | 万濠影像仪(万濠投影仪)百科-苏州林泽仪器 | 蜂窝块状沸石分子筛-吸附脱硫分子筛-萍乡市捷龙环保科技有限公司 | 电镀标牌_电铸标牌_金属标贴_不锈钢标牌厂家_深圳市宝利丰精密科技有限公司 | EDLC超级法拉电容器_LIC锂离子超级电容_超级电容模组_软包单体电容电池_轴向薄膜电力电容器_深圳佳名兴电容有限公司_JMX专注中高端品牌电容生产厂家 | 汽车润滑油厂家-机油/润滑油代理-高性能机油-领驰慧润滑科技(河北)有限公司 | 滚塑PE壳体-PE塑料浮球-警示PE浮筒-宁波君益塑业有限公司 | 鲁尔圆锥接头多功能测试仪-留置针测试仪-上海威夏环保科技有限公司 | 三效蒸发器_多效蒸发器价格_四效三效蒸发器厂家-青岛康景辉 | 12cr1mov无缝钢管切割-15crmog无缝钢管切割-40cr无缝钢管切割-42crmo无缝钢管切割-Q345B无缝钢管切割-45#无缝钢管切割 - 聊城宽达钢管有限公司 | 上海物流公司,上海货运公司,上海物流专线-优骐物流公司 |