Force XDocument to not use namespace prefix if namespace is also defined as default

与世无争的帅哥 提交于 2019-12-23 09:57:10

问题


I have an xml file with default namespace specified with and without namespace prefix. When I generate xml output I'm getting all xml elements prefixed. Is there way to get rid of the prefixes since I'm using the default namespace?

class Program
{
    static void Main(string[] args)
    {
        var xml =
            "<root xmlns='default-namespace' xmlns:key='default-namespace'>" +
            "  <node1></node1>" +
            "  <node2></node2>" +
            "</root>";
        var document = XDocument.Parse(xml);
        var output = document.ToString();
    }
}

The output:

<key:root xmlns="default-namespace" xmlns:key="default-namespace">
  <key:node1></key:node1>
  <key:node2></key:node2>
</key:root>

What I'd expect:

<root xmlns="default-namespace" xmlns:key="default-namespace">
  <node1></node1>
  <node2></node2>
</root>

Unfortunately I can't remove the duplicated namespace declaration. The actual xml file I'm using is provided by another party and I need to do as less modifications as possible.


回答1:


You Can Use String.Replace Method to Get The Required XML Format ...

var xml ="<root xmlns='default-namespace' xmlns:key='default-namespace'>" +
         "  <node1></node1>" +
         "  <node2></node2>" +
         "</root>";
        var document = XDocument.Parse(xml);

        var output = document.ToString().Replace("key:", string.Empty);


来源:https://stackoverflow.com/questions/32632451/force-xdocument-to-not-use-namespace-prefix-if-namespace-is-also-defined-as-defa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!