【问题标题】:XDocument to string: How to omit encoding in declaration?XDocument 到字符串:如何在声明中省略编码?
【发布时间】:2011-11-03 00:52:05
【问题描述】:

我正在为一个脑残的企业 XML API 编写一个包装器。我有一个需要转换为字符串的 XDocument。由于他们的 XML 解析器非常挑剔,以至于它甚至无法处理 XML 节点之间的空白,因此文档声明必须完全正确:

<?xml version="1.0"?>

但是,XDocument.Save() 方法总是在该声明中添加了一个编码属性:

<?xml version="1.0" encoding="utf-16"?>

过去一个小时在 Google 和 Stack 上寻找生成 XML 字符串的最佳方式,我能做的最好的事情是:

string result = xmlStringBuilder.ToString().Replace(@"encoding=""utf-16"", string.Empty));

我试过了

xdoc.Declaration = new XDeclaration("1.0", null, null);

这确实成功地按照我想要的方式在 XDocument 中设置了声明;但是,当我调用 Save() 方法时,无论我走哪条路线(使用 TextWriter、添加 XmlWriterSettings 等),编码属性都会神奇地返回那里。

有没有人有更好的方法来做到这一点,还是我的代码永远注定要在可怕的字符串替换上方的 cmets 中有一段咆哮?

【问题讨论】:

    标签: c# asp.net linq-to-xml


    【解决方案1】:

    如果您想在发布时使用 XML 声明创建一个字符串,那么接收端应该固定为使用 XML 解析器,而不是破坏 XML 语法但使用 .NET 的东西,以下方法适用于我:

    public class MyStringWriter : StringWriter
    {
        public override Encoding Encoding
        {
            get
            {
                return null;
            }
        }
    }
    

    然后

        XDocument doc = new XDocument(
            new XDeclaration("1.0", null, null),
            new XElement("root", "test")
            );
    
        string xml;
    
        using (StringWriter msw = new MyStringWriter())
        {
            doc.Save(msw);
            xml = msw.ToString();
        }
    
        Console.WriteLine(xml);
    

    输出

    <?xml version="1.0"?>
    <root>test</root>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 2012-02-08
      • 2020-02-14
      相关资源
      最近更新 更多