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

0

2

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.

Judejudea answered 21/11, 2013 at 13:40 Comment(7)
I think those prefixes are called namespaces.Dillondillow
possible duplicate of How can I serialize a class with an attributeDillondillow
I think I couldn't tell my problem. I'm gonna edit it now.Judejudea
@MathewFoscarini The prefixes aren't called namespaces--they're called namespace prefixes. The namespace is the URI to which the prefix refers.Vantage
You are right and want to put prefix inside attribute declaration like namespace uri declaration that we did.Judejudea
possible duplicate of XML Serialization and namespace prefixesShall
@AlexFilipovici, I took the example codes from that question. Question is different because I'm asking the solution which is doing by "attributes" not coding. I just want to create my classes and mark their xml output using by attributes... I hope this time my question can understandable.Judejudea

© 2022 - 2024 — McMap. All rights reserved.