C# 通过XmlWriter写入默认xmlns属性的自定义缩进
我正在努力找到用XmlWriter和底层字符串生成器准确编写XML的适当方法:C# 通过XmlWriter写入默认xmlns属性的自定义缩进,c#,xml,xmlwriter,C#,Xml,Xmlwriter,我正在努力找到用XmlWriter和底层字符串生成器准确编写XML的适当方法: <x:node xmlns="uri:default" xmlns:x="uri:special-x" xmlns:y="uri:special-y" y:name="MyNode" SomeOtherAttr="ok"> </x:node> 这创造了 <x:node xmlns:x="uri:specia
<x:node xmlns="uri:default"
xmlns:x="uri:special-x"
xmlns:y="uri:special-y"
y:name="MyNode"
SomeOtherAttr="ok">
</x:node>
这创造了
<x:node
xmlns:x="uri:special-x"
xmlns:y="uri:special-y"
y:name="vd"
SomeOtherAttr="ok" />
但是我找不到一种在节点之后立即编写默认xmlns的方法。任何尝试都会导致错误或格式不同
有什么想法吗?谢谢
更新:也许我可以直接将其写入StringBuilder,但我会寻找更多。。。陛下正确的方法。您需要实际添加默认名称空间,而您目前没有这样做:
var sb = new StringBuilder();
var writer = XmlWriter.Create(sb, new XmlWriterSettings
{
OmitXmlDeclaration = true,
});
using (writer)
{
writer.WriteStartElement("x", "node", "uri:special-x");
writer.WriteAttributeString("xmlns", "uri:default");
writer.Flush();
sb.Append("\n" + new string(' ', 7));
writer.WriteAttributeString("xmlns", "x", null, "uri:special-x");
writer.Flush();
sb.Append("\n" + new string(' ', 7));
writer.WriteAttributeString("xmlns", "y", null, "uri:special-y");
writer.Flush();
sb.Append("\n" + new string(' ', 7));
writer.WriteAttributeString("name", "uri:special-y", "vd");
writer.Flush();
sb.Append("\n" + new string(' ', 7));
writer.WriteAttributeString("SomeOtherAttr", "ok");
writer.WriteEndElement();
}
请参阅此演示:
话虽如此,你为什么要这么做?让它按自己喜欢的方式格式化,它在语义上仍然是一样的,并且完全有效。为什么这么难?
请试试这个:
var r = new StringBuilder();
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
NewLineOnAttributes = true,
Indent = true,
IndentChars = "\t"
};
using (var w = XmlWriter.Create(r, settings))
{
w.WriteStartElement("x", "node", "uri:special-x");
w.WriteAttributeString("xmlns", "x", null, "uri:special-x");
w.WriteAttributeString("xmlns", "y", null, "uri:special-y");
w.WriteAttributeString("name", "uri:special-y", "vd");
w.WriteAttributeString("SomeOtherAttr", "ok");
w.WriteEndElement();
}
所有名称空间都在一行。谢谢,很好。除了名称空间,还有其他类似于NewLineOnAttributes的东西吗?@AlexAtNet不幸的是,没有。我需要比较许多WPF文件,并希望将它们转换为“规范”形式以简化它,并可能将结果用作项目文件的自动格式化工具。为此,文档应该按照VS/Resharper的方式进行格式化,再加上一些“规范”规则,如有序属性等,这是有意义的。通常XML不是供人使用的,但XAML有点特殊!
var r = new StringBuilder();
var settings = new XmlWriterSettings
{
OmitXmlDeclaration = true,
NewLineOnAttributes = true,
Indent = true,
IndentChars = "\t"
};
using (var w = XmlWriter.Create(r, settings))
{
w.WriteStartElement("x", "node", "uri:special-x");
w.WriteAttributeString("xmlns", "x", null, "uri:special-x");
w.WriteAttributeString("xmlns", "y", null, "uri:special-y");
w.WriteAttributeString("name", "uri:special-y", "vd");
w.WriteAttributeString("SomeOtherAttr", "ok");
w.WriteEndElement();
}