使用 XmlAnyAttribute 时反序列化 xml 的值字段没有值 [英] Value field of deserialize xml has no value when using XmlAnyAttribute

查看:33
本文介绍了使用 XmlAnyAttribute 时反序列化 xml 的值字段没有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是 XML 示例,但使用不同的方法来定义属性:

This is the XML sample but using a different approach for defining the attributes:

<TestXML>
   <TestData attr1="MyAttr" attr2="1" DateAdded="">25</TestData>
</TestXML>

现在我的类定义:

public class TestXML() {
   [XmlElement("TestData")]
   public IntegerValue value {get; set;}
}

public class IntegerValue() {
   public int value {get; set;}
   [XmlAnyAttribute]
   public string[] XAttributes {get; set;}
}

现在反序列化的代码:

string xml = "<TestXML><TestData attr1=\"MyAttr\" attr2=\"1\" DateAdded=\"\">25</TestElement> </TestXML>"
using (StringReader sr = new StringReader(xml)) {
   XmlSerializer serializer = new XmlSerializer(typeof(TestXML));
   TestXML myxml = (TestXML)serializer.Deserialize(sr);
}

产生以下结果:

myxml
   value     |  0
   XAttributes  {string[7]}
     [0] "MyAttr"
     [1] "1"
     [2] ""

xml 格式正确.无法使用 XMLAnyAttribute 获取要反序列化的值.想要获取名称以及属性的值,但到目前为止还没有找到该方法的示例.

The xml is formatted correctly. Have not been able to get the value to deserialize using XMLAnyAttribute. Would like to get the name along with the value of the attributes back but haven't found an example of that approach so far.

推荐答案

您可以简单地将 string[] XAttributes 更改为 XmlAttribute[] XAttributes 这将返回整个属性以便您可以访问名称和值

You could simply change string[] XAttributes to XmlAttribute[] XAttributes this will return the whole attribute so you can access Name and Value

public class IntegerValue
{
   public int value {get; set;}

   [XmlAnyAttribute]
   public XmlAttribute[] XAttributes { get; set; }
}

我的测试:

public class TestXML
{
    [XmlElement("TestData")]
    public IntegerValue value { get; set; }
}

public class IntegerValue
{
    public int value { get; set; }

    [XmlAnyAttribute]
    public XmlAttribute[] XAttributes { get; set; }
}


XmlSerializer serializer = new XmlSerializer(typeof(TestXML));
using (FileStream stream = new FileStream(@"C:\StackOverflow.xml", FileMode.Open))
{
    TestXML myxml = (TestXML)serializer.Deserialize(stream);
}

结果:

注意:您发布的xml无效,TestData的结束标签是TestElement,无效

Note: The xml you posted is invalid, the closing tag of TestData is TestElement that wont work

<TestXML>
   <TestData attr1="MyAttr" attr2="1" DateAdded="">25</TestElement>
</TestXML>

应该是

<TestXML>
   <TestData attr1="MyAttr" attr2="1" DateAdded="">25</TestData>
</TestXML>

这篇关于使用 XmlAnyAttribute 时反序列化 xml 的值字段没有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆