【问题标题】:Is it possible to shorten the XDeclaration of an XDocument?是否可以缩短 XDocument 的 XDeclaration?
【发布时间】:2014-06-16 22:23:42
【问题描述】:

我正在向我的 Xdocument 添加一个 XDeclaration,如下所示:

XDocument xml = new XDocument(new XDeclaration("1.0", "utf-8", "yes")

这给了我结果:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>

我正在为 Quickbooks Merchant Services 构建 XML,所以我只需要:

<?xml version="1.0"?>

可以这样做吗?

【问题讨论】:

    标签: c# .net xml quickbooks-online


    【解决方案1】:

    您可以尝试使用不提供任何编码的自定义StringWriter,例如:

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

    然后使用StringWriterNoEncoding 打印XML:

    XDocument xdoc = new XDocument(new XDeclaration("1.0", "", ""), new XElement("Root"));
    var sw = new StringWriterNoEncoding();
    xdoc.Save(sw);
    Console.WriteLine(sw.ToString());
    //above will print :
    //<?xml version="1.0"?>
    //<Root />
    

    【讨论】:

      【解决方案2】:

      无论如何我都需要将其转换为字符串,所以我对我不想留在其中的文本进行了替换:

      string xmlString = xml.Declaration.ToString() + "\n" + xml.ToString();
      xmlString = xmlString.Replace(@" encoding=""utf-8"" standalone=""yes""", "");
      

      【讨论】:

        【解决方案3】:

        这行得通。

        void Main() {
            XDocument xml = new XDocument(new XDeclaration("1.0", "utf-8", ""), new XElement("Root"));
            var sw = new UTF8StringWriter();
            xml.Save(sw);
            Console.WriteLine(sw.GetStringBuilder().ToString());    
        }
        
        private class UTF8StringWriter : StringWriter {
            public override Encoding Encoding { get { return Encoding.UTF8; } }
        }
        

        输出:

        <?xml version="1.0" encoding="utf-8"?> <Root />

        【讨论】:

          【解决方案4】:

          将编码和独立设置为空:

          XDocument xml = new XDocument(new XDeclaration("1.0", null, null)
          

          会给

          <?xml version="1.0"?>
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-09-26
            • 2015-03-26
            • 1970-01-01
            • 2011-08-11
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多