[英]XML serialization with c# & windows forms
我正在嘗試使用Windows窗體創建一個航點生成器,允許用戶通過GUI創建航點和路徑數據並將數據輸出到XML文件。 我選擇利用內置的c#XML序列化功能,但無法以客戶端要求的方式格式化XML輸出。
路標數據對象的剝離版本看起來如下所示:
// Waypoint data class
[XmlRoot("RootNode")]
public class WaypointProjectData
{
[XmlElement("Map")] // Also tried to use XmlElementAttribute,
[XmlAttribute("file")] // XmlAttributeAttribute, and many variations
// of these qualifiers, with no success
public string m_szMapImageFileName;
[XmlAttribute("width")]
public int m_iWidth;
[XmlAttribute("height")]
public int m_iHeight;
[XmlArray("Nodes")]
public ArrayList m_aoNodes;
WaypointProjectData()
{
m_szMapImageFileName = "map.png";
m_aoNodes = new ArrayList();
}
}
客戶端要求XML輸出符合以下布局/格式:
<RootNode>
<Map file="map.png" width="100" height="100" />
<OtherData var="variable" data="10" />
<Nodes>
<Node x="10" y="30" />
<Node x="30" y="20" /> // etc...
</Nodes>
</RootNode>
有關如何使用c#xml序列化執行此操作的一些明確示例將非常有用。 謝謝!
當我必須以這樣的特定Xml格式序列化某些東西時,我從一個模式開始(必要時推斷,如果已知則手工制作)。 然后我使用VS xsd工具來創建序列化類(是的,我知道xsd可以用於推斷架構部分 - 我從來沒有為此目的而煩惱)。
因此,如果您有一個像您的示例創建的xsd文件(請注意,我盡可能多地指定了數據類型 - 這有助於xsd工具使用適當的屬性類型):
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
<xs:element name="RootNode">
<xs:complexType>
<xs:sequence>
<xs:element name="Map">
<xs:complexType>
<xs:attribute name="file" type="xs:string"/>
<xs:attribute name="width" type="xs:decimal"/>
<xs:attribute name="height" type="xs:decimal"/>
</xs:complexType>
</xs:element>
<xs:element name="OtherData">
<xs:complexType>
<xs:attribute name="var" type="xs:string"/>
<xs:attribute name="data" type="xs:decimal"/>
</xs:complexType>
</xs:element>
<xs:element name="Nodes" minOccurs="0">
<xs:complexType>
<xs:sequence>
<xs:element name="Node" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="x" type="xs:decimal"/>
<xs:attribute name="y" type="xs:decimal"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
如果將此命名為Root.xsd,則可以轉到VS命令行並運行
xsd Root.xsd / c /n:myProject.Xml
這將創建一個類文件(名為Root.cs,因為這是處理Root.xsd時的默認值),其中包含可以輕松插入.Net的對象以序列化和反序列化XML。 請注意,我指定了類將具有的命名空間(“/ n:myProject.Xml”)。 我更喜歡控制該命名空間,但其余的默認值通常都很好。 此外,該工具會創建部分類,因此,如果您需要自定義屬性訪問器,則可以將它們添加到單獨的文件中,如果需要再次運行該工具,則該文件將不會被創建。
另一個提示,我在項目中創建了一個名為“<xsd name> xsd Command Line.txt”的文本文件。 這樣我只需要將其粘貼到VS命令行中,而不必記住我使用的其他所有內容。
一旦你走出人跡罕至的序列化是一個巨大的PIA。 你需要標記為map的東西,也可能是OtherData,這意味着你需要一個與節點對應的類或結構。 例如WaypointProejctdata作為類Map,具有屬性filename,width和height。 我的一般經驗法則是,只要我開始搞亂我的對象來獲取xml,序列化就會被分箱,我會添加一個接受XmlReader或Writer並實現它的接口。 嘗試獲取序列化以執行您想要的操作通常是更多代碼,而不是那么易於理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.