How to add prefix in front of xml element using attribute in c#

假如想象 提交于 2019-12-24 01:57:22

问题


with the programming is this:

As a result I want to have this:

<rootprefix:rootname 
     noPrefix="attribute with no prefix"
     firstprefix:attrOne="first atrribute"
     secondprefix:attrTwo="second atrribute with different prefix">

     ...other elements...

 </rootprefix:rootname>

The way to do this by coding is:

NameTable nt = new NameTable();
nt.Add("key");

XmlNamespaceManager ns = new XmlNamespaceManager(nt);
ns.AddNamespace("firstprefix", "fp");
ns.AddNamespace("secondprefix", "sp");

root.SetAttribute("attrOne", ns.LookupPrefix("fp"), "1st attribute");
root.SetAttribute("attrTwo", ns.LookupPrefix("sp"), "2nd with different prefix");

But I want to do this using attributes of types above of the class declaration. For eg: [XmlType(Namespace = "bb:aaaa")] or something else.

How can I do this?

Edit: My class something like this:

[XmlRoot("Node", Namespace="http://flibble")]
public class MyType {
    [XmlElement("chileNode")]
    public string Value { get; set; }
}

And I want to have this result:

<?xml version="1.0" encoding="ibm857"?>
<myNamespace:Node xmlns:myNamespace="http://hede.com" />

Without writing this code:

static class Program
{
    static void Main()
    {
        XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
        ns.Add("myNamespace", "http://hede.com");
        XmlSerializer xser = new XmlSerializer(typeof(MyType));
        xser.Serialize(Console.Out, new MyType(), ns);
    }
}

With some attribute like this:

[XmlRoot("Node", Namespace="http://hede.com", NamespacePrefix="myNamespace")]
public class MyType {
    [XmlElement("chileNode")]
    public string Value { get; set; }
}

But I couldn't find a way putting "myNamespace" prefix in front of xml tag.

来源:https://stackoverflow.com/questions/20122557/how-to-add-prefix-in-front-of-xml-element-using-attribute-in-c-sharp

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