簡體   English   中英

僅使用 xmlns 屬性將 object 序列化為 XML,不帶前綴

[英]Serialize object to XML with xmlns attribute only, without prefix

我需要序列化我的根 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;}
}

像這樣到 XML :

<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>

但我得到這樣的東西:

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

我正在使用這個進行序列化:


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);   
}

當我在不通過 XmlSerializerNamespaces 的情況下進行序列化時,我得到 XML 如下所示:

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

如何在根元素中獲取命名空間,並在 docs 元素中獲取屬性?

您的 Root class 缺少 XmlRoot 屬性:

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

此外,您的其他兩個類不需要 XmlRoot 屬性。

XmlElementAttribute 說“這個字段或屬性代表一個子元素”; XmlRootAttribute 說“這是 XML 文檔的根元素的潛在格式”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM