通过XmlWriter写入时为默认xmlns属性定制缩进

本文关键字:属性 xmlns 缩进 默认 XmlWriter 通过 | 更新日期: 2023-09-27 18:02:08

我有点挣扎,试图找到合适的方式来编写这个XML与XmlWriter和底层字符串生成器:

<x:node xmlns="uri:default"
        xmlns:x="uri:special-x"
        xmlns:y="uri:special-y"
        y:name="MyNode"
        SomeOtherAttr="ok">
</x:node>

目前为止最好的:

static string GetXml()
{
    var r = new StringBuilder();
    var w = XmlWriter.Create(r, new XmlWriterSettings { OmitXmlDeclaration = true });
    w.WriteStartElement("x", "node", "uri:special-x");
    w.Flush();
    r.Append("'n" + new string(' ', 7));
    w.WriteAttributeString("xmlns", "x", null, "uri:special-x");
    w.Flush();
    r.Append("'n" + new string(' ', 7));
    w.WriteAttributeString("xmlns", "y", null, "uri:special-y");
    w.Flush();
    r.Append("'n" + new string(' ', 7));
    w.WriteAttributeString("name", "uri:special-y", "vd");
    w.Flush();
    r.Append("'n" + new string(' ', 7));
    w.WriteAttributeString("SomeOtherAttr", "ok");
    w.Flush();
    w.WriteEndElement();
    w.Flush();
    return r.ToString();
}

<x:node
        xmlns:x="uri:special-x"
        xmlns:y="uri:special-y"
        y:name="vd"
        SomeOtherAttr="ok" />

,但我找不到一种方法来编写默认xmlns后的节点。任何尝试都会导致错误或不同的格式。

任何想法?谢谢!

更新:也许我可以把它直接写到StringBuilder,但我寻找更多…嗯. .正确方法。

通过XmlWriter写入时为默认xmlns属性定制缩进

您需要实际添加您的默认名称空间,这是您目前没有做的:

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

请看这个演示:https://dotnetfiddle.net/994YqW

话虽如此,你为什么要这么做?让它按照自己喜欢的方式格式化,它在语义上仍然是相同的,并且完全有效。

为什么这么难?请试试这个:

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