简体   繁体   中英

Serialize object to XML with xmlns attribute only, without prefix

I need to serialize my Root object:

public class Root{
    [XmlElement(ElementName = "docs", Namespace = "http://example.com/osoz-edi")]
    public Documents Documents{get;set;}
}
[XmlRoot(ElementName = "docs")]
public class Documents {
    [XmlElement(ElementName = "invoice", Namespace = "")]
    public Invoice Invoice{get;set;}
}
[XmlRoot(ElementName = "invoice", Namespace = "")]
public class Invoice {
    [XmlElement(ElementName = "id", Namespace = "")]
    public string Id{get;set;}
    [XmlElement(ElementName = "number", Namespace = "")]
    public string Number{get;set;}
}

to XML like this:

<Root xmlns:ksx="http://example.com/osoz-edi">
    <docs xmlsns="http://example.com/osoz-edi">
        <invoice>
            <id>1</id>
            <number>222</number>
        </invoice>
    </docs>
</Root>

But I get something like this:

<Root xmlns:ksx="http://example.com/osoz-edi">
    <ksx:docs>
        <invoice>
            <id>1</id>
            <number>222</number>
        </invoice>
    </ksx:docs>
</Root>

I'm serializing using this:


var root = new Root(); 
.... //filling object with data
using (var sww = new StringWriter())
using (XmlWriter writer = XmlWriter.Create(sww))
{   
    XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); 
    ns.Add("ksx", "http://example.com/osoz-edi");   
    XmlSerializer xsSubmit = new XmlSerializer(typeof(Stylesheet));
    xsSubmit.Serialize(writer, root, ns);   
}

When I serialize without passing XmlSerializerNamespaces, I get XML like this:

<Root>
    <docs xmlns="http://example.com/osoz-edi">
        <invoice>
            <id>1</id>
            <number>222</number>
        </invoice>
    </docs>
</Root>

How to do get namespace in root element, and attribute in docs element?

Your Root class is missing an XmlRoot attribute:

[XmlRoot(ElementName = "Root", Namespace = "http://example.com/osoz-edi"]
public class Root
{
    // ...
}

Also, your other two classes do not need the XmlRoot attribute.

XmlElementAttribute says "This field or property represents a child element"; XmlRootAttribute says "This is a potential format for the root element of an XML document".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM