如何使用命名空间从xml中提取数据?

时间:2021-08-01 16:02:41

Data ("1.0.0") from attribute "version" fall into property. But the property "Event" in the same class remains empty. If cut namespace from XML, it will work.

属性“version”中的数据(“1.0.0”)属于属性。但是同一个类中的属性“Event”仍然是空的。如果从XML中删除名称空间,它将工作。

My XML:

我的XML:

<rootnode>
  <ns:eventresponse xmlns:ns="somenamespace" version="1.0.0">
    <event id="694717028">
      <somedata>val</somedata>
    </event>
  </ns:eventresponse>
</rootnode>

My class:

我的类:

[XmlRoot("rootnode")]
public class RootNode
{
    [XmlElement(ElementName = "eventresponse", Namespace = "somenamespace")]
    public EventResponseData EventResponse { get; set; }
}

  public class EventResponseData
    {
        [XmlElement("event")]
        public EventData Event { get; set; }

        [XmlAttribute("version")]
        public string Version { get; set; }
    }

public class TvEventData
{
    [XmlAttribute("id")]
    public string EventID { get; set; } 

    [XmlElement("somedata")]
    public string SomeData { get; set; }
}

My Deserializer:

我的反序列化器:

using (var reader = XmlReader.Create(new StringReader(xml)))
{
     reader.MoveToContent();
     var obj = (T)new XmlSerializer(typeof(T)).Deserialize(reader);
} 

1 个解决方案

#1


4  

Your event element is implicitly in the same namespace in the XML due to namespace defaulting, so you should specify that in your declaration:

由于名称空间默认设置,您的事件元素隐式地位于XML中的同一名称空间中,因此您应该在声明中指定:

public class EventResponseData
{
    [XmlElement(ElementName = "event", Namespace = "somenamespace")]
    public EventData Event { get; set; }

    [XmlAttribute("version")]
    public string Version { get; set; }
}

#1


4  

Your event element is implicitly in the same namespace in the XML due to namespace defaulting, so you should specify that in your declaration:

由于名称空间默认设置,您的事件元素隐式地位于XML中的同一名称空间中,因此您应该在声明中指定:

public class EventResponseData
{
    [XmlElement(ElementName = "event", Namespace = "somenamespace")]
    public EventData Event { get; set; }

    [XmlAttribute("version")]
    public string Version { get; set; }
}