作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有以下 XML 结构。 theElement
元素可以包含或不包含 theOptionalList
元素:
<theElement attrOne="valueOne" attrTwo="valueTwo">
<theOptionalList>
<theListItem attrA="valueA" />
<theListItem attrA="anotherValue" />
<theListItem attrA="stillAnother" />
</theOptionalList>
</theElement>
<theElement attrOne="anotherOne" attrTwo="anotherTwo" />
什么是表达相应类结构的简洁方式?
我很确定以下内容:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace MyNamespace
{
public class TheOptionalList
{
[XmlAttributeAttribute("attrOne")]
public string AttrOne { get; set; }
[XmlAttributeAttribute("attrTwo")]
public string AttrTwo { get; set; }
[XmlArrayItem("theListItem", typeof(TheListItem))]
public TheListItem[] theListItems{ get; set; }
public override string ToString()
{
StringBuilder outText = new StringBuilder();
outText.Append("attrOne = " + AttrOne + " attrTwo = " + AttrTwo + "\r\n");
foreach (TheListItem li in theListItems)
{
outText.Append(li.ToString());
}
return outText.ToString();
}
}
}
还有:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
namespace MyNamespace
{
public class TheListItem
{
[XmlAttributeAttribute("attrA")]
public string AttrA { get; set; }
public override string ToString()
{
StringBuilder outText = new StringBuilder();
outText.Append(" attrA = " + AttrA + "\r\n");
return outText.ToString();
}
}
}
但是 theElement
呢?我是否将 theOptionalList
元素作为数组类型让它读取它在文件中找到的内容(什么都没有,或者有一个),然后检查代码是否存在?或者我可以提供其他装饰器吗?还是它只是有效?
编辑: 我最终使用了来自 this answer 的信息.
最佳答案
尝试将 IsNullable = true
添加到 XmlArrayItem
属性。
关于c# - 如何为要与 XmlSerializer 一起使用的可选 XML 元素修饰/定义类成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7934611/
我是一名优秀的程序员,十分优秀!