Hen*_*sel 100 c# linq-to-xml
有没有办法在toString()函数中获取xml编码?
例:
xml.Save("myfile.xml");
Run Code Online (Sandbox Code Playgroud)
导致
<?xml version="1.0" encoding="utf-8"?>
<Cooperations>
<Cooperation>
<CooperationId>xxx</CooperationId>
<CooperationName>Allianz Konzern</CooperationName>
<LogicalCustomers>
Run Code Online (Sandbox Code Playgroud)
但
tb_output.Text = xml.toString();
Run Code Online (Sandbox Code Playgroud)
导致像这样的输出
<Cooperations>
<Cooperation>
<CooperationId>xxx</CooperationId>
<CooperationName>Allianz Konzern</CooperationName>
<LogicalCustomers>
...
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 97
要么明确写出声明,要么使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
您可以轻松地将其添加为扩展方法:
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();
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是,如果没有声明,它就不会爆炸:)
然后你可以使用:
string x = doc.ToStringWithDeclaration();
Run Code Online (Sandbox Code Playgroud)
请注意,这将使用utf-16作为编码,因为这是隐式编码StringWriter
.您可以通过创建子类来自己影响StringWriter
,例如始终使用UTF-8.
Rya*_*ner 45
Declaration属性将包含XML声明.要获取内容和声明,您可以执行以下操作:
tb_output.Text = xml.Declaration.ToString() + xml.ToString()
Run Code Online (Sandbox Code Playgroud)
小智 9
用这个:
output.Text = String.Concat(xml.Declaration.ToString() , xml.ToString())
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
48062 次 |
最近记录: |