我如何反序列化在C#中(的System.Xml.Serialization)XML命名空间? [英] How do I deserialize XML namespaces in C# (System.Xml.Serialization)?

查看:157
本文介绍了我如何反序列化在C#中(的System.Xml.Serialization)XML命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是把收尾到我的 Zthes格式解串器(的System.Xml.Serialization)它使用命名空间直流中的元素THES。所有的术语元素反序列化很好,因为他们没有命名空间,但我无法弄清楚如何以告诉泰晤士报的元素有一个命名空间中的解串器。



下面是我所试图做的(这是不工作),所以希望有人可以给我正确的语法。

  [XmlElement的( 命名空间:someElement)] 
公共字符串someElement;


解决方案

下面是给你一个快速的样本...

  [XmlRoot(myObject的)] 
公共类MyObject的
{
[XmlElement的( myProp,命名空间=http://www.whited.us)]
公共字符串MyProp {搞定;组; }

[XmlAttribute(myOther,命名空间=htt​​p://www.whited.us)]
公共字符串MyOther {搞定;组; }
}

类节目
{
静态无效的主要(字串[] args)
{
变种xnames =新XmlSerializerNamespaces() ;
xnames.Add(W,http://www.whited.us);
变种XSER =新的XmlSerializer(typeof运算(为MyObject));
使用(VAR毫秒=新的MemoryStream())
{
变种MyObj中=新MyObject来()
{
MyProp =你好,
MyOther =世界
};
xser.Serialize(MS,MyObj中,xnames);
VAR解析度= Encoding.ASCII.GetString(ms.ToArray());
/ *
< XML版本=1.0>?;
< myObject的的xmlns:W =htt​​p://www.whited.usW:myOther =世界>
< W:myProp>您好< / W:myProp>
< / myObject的>
* /
}
}
}


I am just putting the finishing touches to my Zthes format deserializer (System.Xml.Serialization) which uses the namespace "dc" in the element "thes". All "term" elements are deserializing fine because they have no namespace but I cannot figure out how to tell the deserializer that the "thes" elements have a namespace.

Here is what I am trying to do (which isn't working) so hopefully someone could give me the proper syntax.

[XmlElement("namespace:someElement")]
public string SomeElement;

解决方案

Here's a quick sample for you...

[XmlRoot("myObject")]
public class MyObject
{
    [XmlElement("myProp", Namespace = "http://www.whited.us")]
    public string MyProp { get; set; }

    [XmlAttribute("myOther", Namespace = "http://www.whited.us")]
    public string MyOther { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var xnames = new XmlSerializerNamespaces();
        xnames.Add("w", "http://www.whited.us");
        var xser = new XmlSerializer(typeof(MyObject));
        using (var ms = new MemoryStream())
        {
            var myObj = new MyObject()
            {
                MyProp = "Hello",
                MyOther = "World"
            };
            xser.Serialize(ms, myObj, xnames);
            var res = Encoding.ASCII.GetString(ms.ToArray());
            /*
                <?xml version="1.0"?>
                <myObject xmlns:w="http://www.whited.us" w:myOther="World">
                  <w:myProp>Hello</w:myProp>
                </myObject>
             */
        }
    }
}

这篇关于我如何反序列化在C#中(的System.Xml.Serialization)XML命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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