默认xmlns属性的自定义缩进将通过XmlWriter写入

时间:2015-07-10 11:11:09

标签: 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>

迄今为止我所做的最好:

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但是我想找更多......嗯..正确的方法。

2 个答案:

答案 0 :(得分:1)

您需要实际添加您当前未执行的默认命名空间:

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

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

答案 1 :(得分:1)

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

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

所有名称空间都在一行上。