gpt4 book ai didi

c# - 如何为要与 XmlSerializer 一起使用的可选 XML 元素修饰/定义类成员?

转载 作者:太空狗 更新时间:2023-10-29 22:28:03 25 4
gpt4 key购买 nike

我有以下 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com