gpt4 book ai didi

c# - 反序列化 :anyType 的列表

转载 作者:数据小太阳 更新时间:2023-10-29 02:40:15 32 4
gpt4 key购买 nike

我有一个由另一个应用程序提供的现有 XML 文件,看起来类似于:

<Root xmlns="http://someNameSpace">
<DisplayName>RootName</DisplayName>
<Groups>
<Group>
<Elements>
<a:anyType i:type="SomeType">
<DisplayName>ElementName</DisplayName>
</a>
</Elements>
</Group>
</Groups>
</Root>

我正在尝试编写一个可以用 XmlSerializer 反序列化的类,目前看起来像这样:

public class Root
{
public string DisplayName { get; set; }
public List<Group> Groups { get; set; }
}

public class Group : SomeType
{
public List<SomeType> Elements { get; set; }
}

public class SomeType
{
public string DisplayName { get; set; }
}

以及使用 XmlSerializer 的简单反序列化代码:

var serializer = new XmlSerializer(typeof (Root));
using (var streamReader = new StreamReader(somePathToXmlFile))
{
root = (Root) serializer.Deserialize(streamReader);
}

反序列化一切正常,除了 Elements列表 - 它总是空的。我试过装饰 Elements属性(property) GroupXmlAttributes通过以下方式:

  1. [XmlArrayItem(ElementName = "a")]
  2. [XmlArrayItem(ElementName = "a:anyType")]
  3. [XmlArrayItem(ElementName = "a", Type = typeof(SomeType))]
  4. [XmlArrayItem(ElementName = "a:anyType", Type = typeof(SomeType))]

到目前为止,没有任何效果。

有谁知道获得 <a:anyType i:type="SomeType"> 的正确方法吗?要反序列化到 Elements 中的项目名单?

编辑从那以后我意识到我遗漏了我的问题是 <Root>实际上有一个命名空间:<Root xmlns="http://someNameSpace"> .请参阅上面的 XML。

最佳答案

考虑在根上添加命名空间声明的 xml

<Root xmlns:a="http://custom/a" xmlns:i="http://custom/i">
<DisplayName>RootName</DisplayName>
<Groups>
<Group>
<Elements>
<a:anyType i:type="SomeType">
<DisplayName>ElementName</DisplayName>
</a:anyType>
</Elements>
</Group>
</Groups>
</Root>

我已经使用以下 xml 属性成功反序列化它:

public class Group : SomeType
{

[XmlArrayItem(typeof(SomeType),ElementName = "anyType", Namespace = "http://custom/a")]
public List<SomeType> Elements { get; set; }
}

public class SomeType
{
[XmlElement(typeof(string),ElementName="DisplayName",Namespace="")]
public string DisplayName { get; set; }
}

或者,如果您不能将 namespace 声明添加到 xml,请使用 XmlNamespaceManager

var serializer = new XmlSerializer(typeof(Root));
var nameTable = new NameTable();
var namespaceManager = new XmlNamespaceManager(nameTable);
namespaceManager.AddNamespace("a", "http://custom/a");
namespaceManager.AddNamespace("i", "http://custom/i");
var parserContext = new XmlParserContext(null, namespaceManager, null, XmlSpace.None);
var settings = new XmlReaderSettings()
{
ConformanceLevel = ConformanceLevel.Fragment

};
using(var fileStream=File.OpenRead(somePathToXmlFile))
{
using(var reader=XmlReader.Create(fileStream,settings,parserContext))
{
var root = (Root)serializer.Deserialize(reader);
}
}

关于c# - 反序列化 :anyType 的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28533984/

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