我想序列化以下Xml结构:
<XmlRootElement>
<Company name="Acme Widgets LLC">
<DbApplication name="ApplicationA" vendor="oracle">
<ConnSpec environment="DEV"
server="DBOraDev1201"
database="AppA"
userId="MyUser"
password="5613456#6%^%$%$#" />
<ConnSpec environment="QA"
server="DBOraQA1205"
database="AppA"
userId="MyUser"
password="5613456#6%^%$%$#" />
</DbApplication>
<DbApplication name="AnotherApp" "vendor="SQLServer">
<ConnSpec environment="DEV"
server="DBMsSqlDev1201"
catalog="AnoptherApp"
userId="MyUser"
password="5613456#6%^%$%$#" />
<ConnSpec environment="QA"
server="DBMsSqlQA1565"
catalog="AnotherApp"
userId="MyUser"
password="5613456#6%^%$%$#" />
</DbApplication>
</Company>
<Company name = "ExpertSoftware Inc" ....
...
</Company>
</XmlRootElement>
但我在link text
中发现了从以上链接引用: ...
...
发现您无法序列化或反序列化其中包含其他Xml属性的集合...建议的解决方法是将具有集合的元素与具有其他属性的元素分开...即,你必须改变结构,使它看起来像这样:
<XmlRootElement>
<Companys>
<Company name="Acme Widgets LLC">
<DbApplications>
<DbApplication name="ApplicationA" vendor="oracle">
<ConnSpecs>
<ConnSpec environment="DEV"
server="DBOraDev1201" ... />
<ConnSpec environment="QA"
server="DBOraQA1205"
database="AppA" ... />
</ConnSpecs>
</DbApplication>
<DbApplication name="AnotherApp" "vendor="SQLServer">
<ConnSpecs>
<ConnSpec environment="DEV" ... />
<ConnSpec environment="QA" ... />
</ConnSpecs>
</DbApplication>
</DbApplications>
</Company>
<Company name = "ExpertSoftware Inc" ....
...
</Company>
</Companys>
</XmlRootElement>
有谁知道为什么会这样?或者如果有其他方法可以做到这一点?
答案 0 :(得分:2)
如果您使用XmlSerializer,则需要指明如何序列化您的收藏品:
public class XmlRootElement
{
[XmlElement(ElementName="Company")]
public Company[] Company { get; set; }
// Other properties ....
}
public class Company
{
[XmlAttribute(AttributeName="name")]
public string Name { get; set; }
[XmlElement(ElementName = "DbApplication")]
public DbApplication[] DbApplication { get; set; }
// Other properties ....
}
public class DbApplication
{
[XmlElement(ElementName = "ConnSpec")]
public ConnSpec[] ConnSpec { get; set; }
// Other properties ....
}
public class ConnSpec
{
// Other properties ....
}
然后:
using (Stream stream = new FileStream("test.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
{
XmlSerializer serializer = new XmlSerializer(typeof(XmlRootElement));
XmlRootElement root = (XmlRootElement)serializer.Deserialize(stream);
}
希望这有帮助。
答案 1 :(得分:1)
将XMl序列化属性添加到所有类的替代方法是在根元素容器类上实现IXmlSerializable接口。 XmlSerializer将使用此接口的 ReadXml 和 WriteXml 方法,使您可以对序列化/反序列化过程进行更细粒度的控制。