C# XDocument.ToString() 删除 XML 编码标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1228976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XDocument.ToString() drops XML Encoding Tag
提问by Henrik P. Hessel
Is there any way to get the xml encoding in the toString() Function?
有没有办法在 toString() 函数中获取 xml 编码?
Example:
例子:
xml.Save("myfile.xml");
leads to
造成
<?xml version="1.0" encoding="utf-8"?>
<Cooperations>
<Cooperation>
<CooperationId>xxx</CooperationId>
<CooperationName>Allianz Konzern</CooperationName>
<LogicalCustomers>
But
但
tb_output.Text = xml.toString();
leads to an output like this
导致这样的输出
<Cooperations>
<Cooperation>
<CooperationId>xxx</CooperationId>
<CooperationName>Allianz Konzern</CooperationName>
<LogicalCustomers>
...
采纳答案by Jon Skeet
Either explicitly write out the declaration, or use a StringWriter
and call Save()
:
要么明确写出声明,要么使用 aStringWriter
和 call 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);
}
}
You could easily add that as an extension method:
您可以轻松地将其添加为扩展方法:
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();
}
This has the advantage that it won't go bang if there isn'ta declaration :)
这样做的好处是,如果没有声明,它就不会爆炸:)
Then you can use:
然后你可以使用:
string x = doc.ToStringWithDeclaration();
Note that that will use utf-16 as the encoding, because that's the implicit encoding in StringWriter
. You can influence that yourself though by creating a subclass of StringWriter
, e.g. to always use UTF-8.
请注意,这将使用 utf-16 作为编码,因为这是StringWriter
. 您可以通过创建 的子类来影响自己StringWriter
,例如始终使用 UTF-8。
回答by Ryan Brunner
The Declaration property will contain the XML declaration. To get the contents plus declaration, you can do the following:
声明属性将包含 XML 声明。要获取内容加声明,您可以执行以下操作:
tb_output.Text = xml.Declaration.ToString() + xml.ToString()
回答by Gus Paul
You can also use an XmlWriter and call the
您还可以使用 XmlWriter 并调用
Writer.WriteDocType()
method.
方法。
回答by Farooq Kaiser
use this:
用这个:
output.Text = String.Concat(xml.Declaration.ToString() , xml.ToString())
回答by Ziggler
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());
Please see below for what I get in distributorInfo
请看下面我在distributorInfo中得到的信息
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Distributors>
<Distributor Id="12345678" />
<Distributor Id="22222222" />
<Distributor Id="11111111" />
</Distributors>
回答by sonjz
Similar to the other +1 answers, but a bit more detail about the declaration, and a slightly more accurate concatenation.
与其他 +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
<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() ;
Both results produce:
两个结果都产生:
<?xml version="1.0" encoding="iso-8859-1"?>
<rss version="2.0"></rss>
回答by B2K
A few of these answers solve the poster's request, but seem overly complicated. Here's a simple extension method that avoids the need for a separate writer, handles a missing declaration and supports the standard ToString SaveOptions parameter.
其中一些答案解决了发布者的要求,但似乎过于复杂。这是一个简单的扩展方法,它不需要单独的编写器,处理丢失的声明并支持标准的 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()
要使用扩展名,只需替换xml.ToString()
为xml.ToXmlString()
回答by David
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