我会尝试一些应该消除属性焦虑的东西。
生成(或使用现有的)适用于您的 XML 的 XSD。像这样的东西:
<?xml version="1.0" encoding="utf-8"?>
<!--XML Schema generated by QTAssistant/XML Schema Refactoring (XSR) Module (http://www.paschidev.com)-->
<xsd:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="dimensions">
<xsd:complexType>
<xsd:sequence>
<xsd:element maxOccurs="unbounded" name="dimensions">
<xsd:complexType>
<xsd:attribute name="id" type="xsd:unsignedByte" use="required" />
<xsd:attribute name="name" type="xsd:string" use="required" />
<xsd:attribute name="serverAddress" type="xsd:string" use="required" />
<xsd:attribute name="port" type="xsd:unsignedShort" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
使用 .NET 提供的 xsd.exe 工具(Visual Studio 命令提示符会很好地为您设置路径)生成类(假设上述 XSD 保存为converting-xml-into-a-c-sharp-object.xsd
):
xsd /c <fullpath-if-not-in-the-current-folder>converting-xml-into-a-c-sharp-object.xsd
生成的代码将类似于(只是标题):
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.17929
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System.Xml.Serialization;
//
// This source code was auto-generated by xsd, Version=4.0.30319.1.
//
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)]
public partial class dimensions {
private dimensionsDimensions[] dimensions1Field;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("dimensions")]
public dimensionsDimensions[] dimensions1 {
get {
return this.dimensions1Field;
}
set {
this.dimensions1Field = value;
}
}
}
下一步是编写引用这个生成的类的代码;您可以找到很多参考资料;SO 上的介绍可能是这样的。
上面的 XSD(“Russian Doll”)创作风格给看起来不聪明的类命名;这是一种可能的解决方法。