zoukankan      html  css  js  c++  java
  • XML 解析默认去掉命名空间和注释

      注:最近在写xml操作这块东西,中间遇到了一些坑 其中就包含下面一个 遇到xml文件包含 命名空间或者注释 这时反序列化 会报错。下面就是解决方案
    1 //创建xml文档

      2 XmlDocument xmlDoc = new XmlDocument();

      3 xmlDoc.Load(@"C:UsersTonyDownloads统一标准报文格式.xml");

      4 //去掉注释 和命名空间

      5 string newXml = System.Text.RegularExpressions.Regex.Replace(

      6 xmlDoc.OuterXml,

      7 @"(xmlns:?[^=]*=[""][^""]*[""])", "",

      8 System.Text.RegularExpressions.RegexOptions.IgnoreCase |

      9 System.Text.RegularExpressions.RegexOptions.Multiline);

      10         //这里是反序列化成实体

      11        root info= XmlHelper.ToObject(newXml);

    复制代码

      1 ///

      2 /// XML帮助类

      3 ///

      4 public class XmlHelper

      5 {

      6 ///

      7 /// xml转实体

      8 ///

      9 ///

      10 ///xml字符串

      11 ///

      12 public static T ToObject(string content) where T : new()

      13 {

      14 using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)))

      15 {

      16 XmlSerializer xmlFormat = new XmlSerializer(typeof(T));

      17 return (T)xmlFormat.Deserialize(stream);

      18 }

      19 }

      20

      21 ///

      22 /// 实体转xml

      23 ///

      24 ///

      25 ///

      26 ///

      27 public static string ToXml(T t) where T : new()

      28 {

      29 XmlSerializer xmlSerializer = new XmlSerializer(t.GetType());

      30 Stream stream = new MemoryStream();

      31 xmlSerializer.Serialize(stream, t);

      32 stream.Position = 0;

      33 StreamReader reader = new StreamReader(stream);

      34 string text = reader.ReadToEnd();

      35 return text;

      36 }

      37 }

      复制代码(编辑:雷林鹏 来源:网络)

  • 相关阅读:
    stl 在 acm中的应用总结
    hdu_2089(数位dp)
    水dp第二天(背包有关)
    dp水一天
    poj_2195Going Home(最小费用最大流)
    poj_3281Dining(网络流+拆点)
    GSS4
    SPOJ GSS1_Can you answer these queries I(线段树区间合并)
    Ajax实现局部数据交互的一个简单实例
    对学习Ajax的知识总结
  • 原文地址:https://www.cnblogs.com/pengpeng1208/p/9441130.html
Copyright © 2011-2022 走看看