C# 如何使用无声明元素的xml编写器创建xml
我正在使用C# 如何使用无声明元素的xml编写器创建xml,c#,.net,xml,xmlwriter,C#,.net,Xml,Xmlwriter,我正在使用XmlWriter.Create()获取一个writer实例,然后编写XML,但结果是,如何告诉我的XML编写器不生成它 使用 不要忘记设置为ConformanceLevel.Fragment您可以子类化XmlTextWriter并重写WriteStartDocument()方法以不执行任何操作: public class XmlFragmentWriter : XmlTextWriter { // Add whichever constructor(s) you need,
XmlWriter.Create()
获取一个writer实例,然后编写XML,但结果是
,如何告诉我的XML编写器不生成它 使用
不要忘记设置为
ConformanceLevel.Fragment
您可以子类化XmlTextWriter
并重写WriteStartDocument()
方法以不执行任何操作:
public class XmlFragmentWriter : XmlTextWriter
{
// Add whichever constructor(s) you need, e.g.:
public XmlFragmentWriter(Stream stream, Encoding encoding) : base(stream, encoding)
{
}
public override void WriteStartDocument()
{
// Do nothing (omit the declaration)
}
}
用法:
var stream = new MemoryStream();
var writer = new XmlFragmentWriter(stream, Encoding.UTF8);
// Use the writer ...
参考:这是斯科特·汉斯曼的作品 您可以将
XmlWriter.Create()
用于:
new XmlWriterSettings {
OmitXmlDeclaration = true,
ConformanceLevel = ConformanceLevel.Fragment
}
public static string FormatXml(string xml)
{
if (string.IsNullOrEmpty(xml))
return string.Empty;
try
{
XmlDocument document = new XmlDocument();
document.LoadXml(xml);
using (MemoryStream memoryStream = new MemoryStream())
using (XmlWriter writer = XmlWriter.Create(
memoryStream,
new XmlWriterSettings {
Encoding = Encoding.Unicode,
OmitXmlDeclaration = true,
ConformanceLevel = ConformanceLevel.Fragment,
Indent = true,
NewLineOnAttributes = false }))
{
document.WriteContentTo(writer);
writer.Flush();
memoryStream.Flush();
memoryStream.Position = 0;
using (StreamReader streamReader = new StreamReader(memoryStream))
{
return streamReader.ReadToEnd();
}
}
}
catch (XmlException ex)
{
return "Unformatted Xml version." + Environment.NewLine + ex.Message;
}
catch (Exception ex)
{
return "Unformatted Xml version." + Environment.NewLine + ex.Message;
}
}
从您链接到的文档中:
如果ConformanceLevel设置为Document,则XML声明始终会写入,即使OmitXmlDeclaration设置为true,也会写入。
大部分时间不会设置为Document吗?@Cameron,奇怪的问题ConformanceLevel.Document
是默认值,但您可以设置ConformanceLevel.Fragment
…啊,是的,我知道:-)您可能想将其添加到您的答案中。如果您想要文档一致性级别(例如,确保单个根节点),但不需要XML声明,该怎么办?@Cameron,我想您自己已经回答了您的问题:-)谢谢,还有更好的方法吗?我不想为了删除声明而创建子类。@ninithepug:据我所知,对不起。不过,如果您经常使用它,您可以在某个地方将其封装为静态方法。这应该有助于保持它clean@ninithepug:Kirill的答案(不需要新类)似乎更好(当然,除非您想要文档一致性级别)。