gpt4 book ai didi

c# - 无法反序列化此 xml 的所有元素

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:08 25 4
gpt4 key购买 nike

此 XML 的少数元素不会反序列化,但也不会抛出任何错误。

<?xml version="1.0" encoding="utf-8"?>
<TrialMWordsRecord xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MyList>
<MWords>
<Id>0</Id>
<Name>ListMWords1</Name>
<Type>LIST</Type>
<MyOutput>true</MyOutput>
<WordsElements>
<Words>
<Name>ListMWords1</Name>
<Value>Apple</Value>
<Type>STRING</Type>
</Words>
<Words>
<Name>ListMWords1</Name>
<Value>Mango</Value>
<Type>STRING</Type>
</Words>
<Words>
<Name>ListMWords1</Name>
<Value>Chickoo</Value>
<Type>STRING</Type>
</Words>
</WordsElements>
</MWords>
<MWords>
<Id>1</Id>
<Type>RANDOM</Type>
<MyOutput>true</MyOutput>
<WordsElements>
<Name>Limit</Name>
<Value>3,8</Value>
<Type>NUMERIC</Type>
</WordsElements>
</MWords>
</TrialMWordsList>
</MyListRecord>

以下是我的类(class):

[Serializable()]
[XmlRootAttribute("MyListRecord")]
public class MyList
{

[XmlArray("MyList")]
public List<MWords> MWords
{
get;
set;
}

public static MyList Deserialize()
{
XmlSerializer deserializer = new XmlSerializer(typeof(MyList));
TextReader textReader = new StreamReader(Application.StartupPath + "\\MyList.xml");

MyList resultList = (MyList)deserializer.Deserialize(textReader);

textReader.Close();

return resultList;
}
}

[Serializable()]
public class MWords
{

public int Id
{
get;
set;
}

public MWordsType Type
{
get;
set;
}

public bool MyOutput
{
get;
set;
}

public string Requirement
{
get;
set;
}

[XmlArrayItem("WordsElements")]
public List<Words> WordList
{
get;
set;
}

public static MWords Deserialize()
{
XmlSerializer deserializer = new XmlSerializer(typeof(MWords));
TextReader textReader = new StreamReader(Application.StartupPath + "\\MWords.xml");
MWords mwords = (MWords)deserializer.Deserialize(textReader);
textReader.Close();
return mwords;
}
}

public class Words
{
public string Value
{
get;
set;
}

public TYPE Type
{
get;
set;
}

public string Name
{
get;
set;
}
}

现在当我反序列化这个 XML 时,如果 Type 是 LiST,WordList 会更新,例如这里 WordList 的计数将为 3,但如果 Type 是 RANDOM,则 WordList 为 0,这实际上应该是 1 而不是 0。真的不知道可能是什么原因。

最佳答案

问题出在您的 XML 中。查看您的工作案例的情况:

<WordsElements>
<Words>
<Name>ListMWords1</Name>
<Value>Apple</Value>
<Type>STRING</Type>
</Words>
<Words>
...
</Words>
<Words>
...
</Words>
</WordsElements>

现在将它与破损的箱子进行比较:

<WordsElements>
<Name>Limit</Name>
<Value>3,8</Value>
<Type>NUMERIC</Type>
</WordsElements>

你没有 Words 元素 - 它应该是:

<WordsElements>
<Words>
<Name>Limit</Name>
<Value>3,8</Value>
<Type>NUMERIC</Type>
</Words>
</WordsElements>

如果您不能更改 XML,您可能需要手动反序列化它 - 这可能不会太难。

顺便说一句,您可能想考虑在一行中编写自动实现的属性 - 这样写起来很多更紧凑

public string Name { get; set; }

public string Name
{
get;
set;
}

...而且它并不难读,IMO。

关于c# - 无法反序列化此 xml 的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26730363/

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