c#具有两个同名元素但不同属性的XML
我得到了一个XML,其中包含两个具有相同NAMEM的元素,即“ log”,但是每个“ log”元素具有不同的属性名称。例如,第一个“ log”元素具有属性名称“ attra”,而第二个“ log”元素具有“ attrb”。我已经尝试使用XMlarrayItem,但不要在数组中阅读它。在下面的代码中,“ MyObjectWithOutLog”对象包含ELM,但不包含日志数据。有人知道我如何将两个日志元素放入序列化对象中?
xml
<Elm DbLocation="C:\Data\Db\My.db">
<Log AttrA="C:\Data\Log\Log1.csv"/>
<Log AttrA="C:\Data\Log\Log2.csv"/>
</Elm>
c#
[XmlRoot(ElementName = "Elm", Namespace = "")]
public class myXmlObject
{
public myXmlObject()
{
}
[XmlAttribute("DbLocation", Namespace = "")]
public string DbLocation { get; set; }
[XmlArrayItem("Log", Namespace = "")]
public List<Log> logs { get; set; }
}
[XmlRoot(ElementName = "Log", Namespace = "")]
public class Log
{
[XmlAttribute("AttrA", Namespace = "")]
public string attrA { get; set; }
[XmlAttribute("AttrB", Namespace = "")]
public string attrB { get; set; }
}
public class RunIt
{
XmlSerializer serializer = new XmlSerializer(typeof(myXmlObject));
using (FileStream stream = new FileStream(myXmlFile, FileMode.Open))
{
myXmlObject myObjectWithoutLog = (myXmlObject)serializer.Deserialize(stream);
}
}
I've been given an xml containing two elements that have the same namem, 'Log', but where each 'Log' element has different attribute names. E.g. the first 'Log' element has attribute name 'AttrA' and the second 'Log' element has 'AttrB'. I've tried using XmlArrayItem, but don't get it to read in the array. In the code below, the 'myObjectWithoutLog' object contains Elm, but not the Log data. Anybody know how I can get the two Log elements into the serialized object?
XML
<Elm DbLocation="C:\Data\Db\My.db">
<Log AttrA="C:\Data\Log\Log1.csv"/>
<Log AttrA="C:\Data\Log\Log2.csv"/>
</Elm>
C#
[XmlRoot(ElementName = "Elm", Namespace = "")]
public class myXmlObject
{
public myXmlObject()
{
}
[XmlAttribute("DbLocation", Namespace = "")]
public string DbLocation { get; set; }
[XmlArrayItem("Log", Namespace = "")]
public List<Log> logs { get; set; }
}
[XmlRoot(ElementName = "Log", Namespace = "")]
public class Log
{
[XmlAttribute("AttrA", Namespace = "")]
public string attrA { get; set; }
[XmlAttribute("AttrB", Namespace = "")]
public string attrB { get; set; }
}
public class RunIt
{
XmlSerializer serializer = new XmlSerializer(typeof(myXmlObject));
using (FileStream stream = new FileStream(myXmlFile, FileMode.Open))
{
myXmlObject myObjectWithoutLog = (myXmlObject)serializer.Deserialize(stream);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在使用错误的XML属性。您需要使用 Xmlelement 而不是 xmlarrayitem 。
You're using wrong Xml attribute. You need to use XmlElement instead of XmlArrayItem.