代码之家  ›  专栏  ›  技术社区  ›  Henrik P. Hessel

xdocument.toString()删除XML编码标记

  •  95
  • Henrik P. Hessel  · 技术社区  · 16 年前

    在toString()函数中有没有任何方法可以获得XML编码?

    例子:

    xml.Save("myfile.xml");
    

    导致

    <?xml version="1.0" encoding="utf-8"?>
    <Cooperations>
      <Cooperation>
        <CooperationId>xxx</CooperationId>
        <CooperationName>Allianz Konzern</CooperationName>
        <LogicalCustomers>
    

    但是

    tb_output.Text = xml.toString();
    

    导致这样的输出

    <Cooperations>
      <Cooperation>
        <CooperationId>xxx</CooperationId>
        <CooperationName>Allianz Konzern</CooperationName>
        <LogicalCustomers>
        ...
    
    8 回复  |  直到 6 年前
        1
  •  94
  •   Community CDub    8 年前

    要么显式写出声明,要么使用 StringWriter 并打电话 Save() :

    using System;
    using System.IO;
    using System.Text;
    using System.Xml.Linq;
    
    class Test
    {
        static void Main()
        {
            string xml = @"<?xml version='1.0' encoding='utf-8'?>
    <Cooperations>
      <Cooperation />
    </Cooperations>";
    
            XDocument doc = XDocument.Parse(xml);
            StringBuilder builder = new StringBuilder();
            using (TextWriter writer = new StringWriter(builder))
            {
                doc.Save(writer);
            }
            Console.WriteLine(builder);
        }
    }
    

    您可以很容易地将其添加为扩展方法:

    public static string ToStringWithDeclaration(this XDocument doc)
    {
        if (doc == null)
        {
            throw new ArgumentNullException("doc");
        }
        StringBuilder builder = new StringBuilder();
        using (TextWriter writer = new StringWriter(builder))
        {
            doc.Save(writer);
        }
        return builder.ToString();
    }
    

    这样做的好处是,如果有,它就不会爆炸。 不是 声明:)

    然后您可以使用:

    string x = doc.ToStringWithDeclaration();
    

    请注意,这将使用UTF-16作为编码,因为这是 架线作家 . 你可以通过创建一个 架线作家 ,例如 to always use UTF-8 .

        2
  •  43
  •   Ryan Brunner    16 年前

    声明属性将包含XML声明。要获取内容加声明,可以执行以下操作:

    tb_output.Text = xml.Declaration.ToString() + xml.ToString()
    
        3
  •  9
  •   Gonzalo.-    12 年前

    使用此:

    output.Text = String.Concat(xml.Declaration.ToString() , xml.ToString())
    
        4
  •  3
  •   Ziggler    10 年前

    我喜欢这样

            string distributorInfo = string.Empty;
    
            XDocument distributors = new XDocument();
    
         //below is important else distributors.Declaration.ToString() throws null exception
            distributors.Declaration = new XDeclaration("1.0", "utf-8", "yes"); 
    
            XElement rootElement = new XElement("Distributors");
            XElement distributor = null;
            XAttribute id = null;
    
            distributor = new XElement("Distributor");
            id = new XAttribute("Id", "12345678");
            distributor.Add(id);
            rootElement.Add(distributor);
    
            distributor = new XElement("Distributor");
            id = new XAttribute("Id", "22222222");
    
            distributor.Add(id);
    
            rootElement.Add(distributor);         
    
            distributors.Add(rootElement);
    
            distributorInfo = String.Concat(distributors.Declaration.ToString(), distributors.ToString());
    

    请看下面我在DistributorInfo中得到的信息

    <?xml version="1.0" encoding="utf-8" standalone="yes"?>
    <Distributors>
      <Distributor Id="12345678" />
      <Distributor Id="22222222" />
      <Distributor Id="11111111" />
    </Distributors>
    
        5
  •  2
  •   sonjz    9 年前

    与其他+1答案类似,但对声明有一点更详细的说明,并稍微更准确地连接起来。

    <xml /> 声明应该在格式化的XML中位于它自己的行上,所以我要确保添加了换行符。 注:使用 Environment.Newline 因此,它将生成特定于平台的新行

    // Parse xml declaration menthod
    XDocument document1 =
      XDocument.Parse(@"<?xml version=""1.0"" encoding=""iso-8859-1""?><rss version=""2.0""></rss>");
    string result1 =
      document1.Declaration.ToString() +
      Environment.NewLine +
      document1.ToString() ;
    
    // Declare xml declaration method
    XDocument document2 = 
      XDocument.Parse(@"<rss version=""2.0""></rss>");
    document2.Declaration =
      new XDeclaration("1.0", "iso-8859-1", null);
    string result2 =
      document2.Declaration.ToString() +
      Environment.NewLine +
      document2.ToString() ;
    

    两种结果都会产生:

    <?xml version="1.0" encoding="iso-8859-1"?>
    <rss version="2.0"></rss>
    
        6
  •  0
  •   Adriano Carneiro Tigran    14 年前

    也可以使用XmlWriter并调用

    Writer.WriteDocType() 
    

    方法。

        7
  •  0
  •   B2K    8 年前

    其中一些答案解决了海报的要求,但似乎过于复杂。这里有一个简单的扩展方法,它可以避免需要单独的编写器,处理缺少的声明,并支持标准的ToString SaveOptions参数。

    public static string ToXmlString(this XDocument xdoc, SaveOptions options = SaveOptions.None)
    {
        var newLine =  (options & SaveOptions.DisableFormatting) == SaveOptions.DisableFormatting ? "" : Environment.NewLine;
        return xdoc.Declaration == null ? xdoc.ToString(options) : xdoc.Declaration + newLine + xdoc.ToString(options);
    }
    

    要使用扩展名,只需替换 xml.ToString() 具有 xml.ToXmlString()

        8
  •  0
  •   David    6 年前
    string uploadCode = "UploadCode";
    string LabName = "LabName";
    XElement root = new XElement("TestLabs");
    foreach (var item in returnList)
    {  
           root.Add(new XElement("TestLab",
                    new XElement(uploadCode, item.UploadCode),
                    new XElement(LabName, item.LabName)
                                )
                   );
    }
    
    XDocument returnXML = new XDocument(new XDeclaration("1.0", "UTF-8","yes"),
                 root);
    
    string returnVal;
    using (var sw = new MemoryStream())
    {
           using (var strw = new StreamWriter(sw, System.Text.UTF8Encoding.UTF8))
           {
                  returnXML.Save(strw);
                  returnVal = System.Text.UTF8Encoding.UTF8.GetString(sw.ToArray());
           }
    }
    
    // ReturnVal has the string with XML data with XML declaration tag