ToString()删除 XML 编码标记

有没有办法在 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>
...
53617 次浏览

Declaration 属性将包含 XML 声明:

tb_output.Text = xml.Declaration.ToString() + xml.ToString()

还可以使用 XmlWriter 并调用

Writer.WriteDocType()

方法。

要么显式地写出声明,要么使用 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作为编码,因为这是 StringWriter中的隐式编码。你可以通过创建一个 StringWriter的子类,例如 to always use UTF-8来影响你自己。

使用:

output.Text = String.Concat(xml.Declaration.ToString() , xml.ToString())

I did like this

        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());

请看下面我在经销商信息中得到了什么

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Distributors>
<Distributor Id="12345678" />
<Distributor Id="22222222" />
<Distributor Id="11111111" />
</Distributors>

与其他 + 1答案类似,但是声明更加详细,而且连接也更加精确。

<xml /> declaration should be on its own line in a formatted XML, so I'm making sure we have the newline added. NOTE: using Environment.Newline so it will produce the platform specific 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>

其中一些答案解决了海报的要求,但似乎过于复杂。下面是一个简单的扩展方法,它可以避免使用单独的编写器,处理缺少的声明,并支持标准的 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);
}

To use the extension, just replace xml.ToString() with xml.ToXmlString()

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

扩展方法来获得包含的 Xml 声明,在这里使用字符串插值,并选择在 Xml 声明后添加一个新行,因为这是我猜测的标准。

public static class XDocumentExtensions {
        

public static string ToStringIncludeXmlDeclaration(this XDocument doc){
return $"({((doc.Declaration != null ? doc.Declaration.ToString() +
Environment.NewLine : string.Empty) + doc.ToString())}";
}
}
}

用法:

tb_output.Text = xml.ToStringIncludeXmlDeclaration();