1
我遇到了使用.net XMLSerializer對象和XML命名空間的問題。我對XMLSerializer的使用經驗非常有限,而且我之前沒有使用XML。我試圖像下面這樣:.net XMLSerializer多個命名空間問題
<Record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Property1>blah</Property1>
<oai_dc:dc xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/" xmlns:dc="http://purl.org/dc/elements/1.1/">>
<dc:Property2>asdsd</dc:Property2>
<dc:Property3>asdasasdda</dc:Property3>
</oai_dc:dc>
</Record>
不過,我可以在瞬間獲得最佳的是(注意命名空間聲明的位置)
<Record xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:oai_dc="http://www.openarchives.org/OAI/2.0/oai_dc/" xmlns:dc="http://purl.org/dc/elements/1.1/">
<Property1>blah</Property1>
<oai_dc:dc>
<dc:Property2>asdsd</dc:Property2>
<dc:Property3>asdasasdda</dc:Property3>
</oai_dc:dc>
</Record>
的命名空間中被宣佈根元素,而不是我喜歡的dc元素。我明白,要麼在根中聲明命名空間,要麼在使用命名空間的元素中應該是可以接受的。
我附加了XMLSerializerNamespaces如下:
Dim XMLNamespaces As New XmlSerializerNamespaces()
XMLNamespaces.Add("oai_dc", "http://www.openarchives.org/OAI/2.0/oai_dc/")
XMLNamespaces.Add("dc", "http://purl.org/dc/elements/1.1/")
XMLNamespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance")
XMLSerializer.Serialize(XMLWriter, inputObject, XMLNamespaces)
和我使用的對象如下:
<XmlRoot("Record")> _
Public Class Record
<XmlElement("Property1")> _
Public Property1 As String
<XmlElement("dc", Namespace:="http://www.openarchives.org/OAI/2.0/oai_dc/")> _
Public DCMetadata As DublinCore
Public Sub New()
DCMetadata = New DublinCore()
End Sub
End Class
<XmlRoot("dc", Namespace:="http://www.openarchives.org/OAI/2.0/oai_dc/")> _
Public Class DublinCore
<XmlElement("Property2", Namespace:="http://purl.org/dc/elements/1.1/")> _
Public Property2 As String
<XmlElement("Property3", Namespace:="http://purl.org/dc/elements/1.1/")> _
Public Property3 As String
Public Sub New()
End Sub
End Class
有沒有什麼辦法來迫使XMLSerializer的輸出命名空間對樹下的元素進行聲明?
感謝您的任何輸入,
安迪