更改/重命名名称空间前缀

时间:2012-11-06 16:10:57

标签: c# namespaces linq-to-xml xelement

我有一个包含这些元素的XELEMENT

<customer>
    <ns8:title xmlns:ns8="http://ws.xxx.com/xxx/model/common">B< /ns8:title>
    <ns9:firstname xmlns:ns9="http://ws.xxx.com/xxx/model/common">Bob< /ns9:firstname>
    <ns10:lastname xmlns:ns10="http://ws.xxx.com/xxx/model/common">Petier< /ns10:lastname>
    <ns11:bday xmlns:ns11="http://ws.xxx.com/xxx/model/common">19310227< /ns11:bday>
    <ns12:rank xmlns:ns12="http://ws.xxx.com/xxx/model/common">1< /ns12:rank>
</customer>

我想像这样转换前缀。

<customer>
    <ns1:title xmlns:ns1="http://ws.xxx.com/xxx/model/common">B< /ns1:title>
    <ns2:firstname xmlns:ns2="http://ws.xxx.com/xxx/model/common">Bob< /ns2:firstname>
    <ns3:lastname xmlns:ns3="http://ws.xxx.com/xxx/model/common">Petier< /ns3:lastname>
    <ns4:bday xmlns:ns4="http://ws.xxx.com/xxx/model/common">19310227< /ns4:bday>
    <ns5:rank xmlns:ns5="http://ws.xxx.com/xxx/model/common">1< /ns5:rank>
< /customer>

我试图删除属性,但没有运气..

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您应该删除现有的命名空间定义属性(如果有)并添加一个新属性:

element.Add(new XAttribute(XNamespace.Xmlns + "ns1", "http://ws.xxx.com/xxx/model/common"));

通过添加显式命名空间属性,您将强制XElement将其用于序列化。