【问题标题】:Deserialize XML Not Working contains xmlns反序列化 XML 不工作包含 xmlns
【发布时间】:2020-09-26 21:03:11
【问题描述】:

这是我的 xml 字符串。

<test name="james" type="seoul" xmlns="test:client">
    <friends xmlns="friends:test">
        <friend xmlns="" name="john">
            Google
        </friend>
        <friend xmlns="" name="john">
            Amazon
        </friend>
    </friends>
</test>

我在后面尝试了这段代码。

[Serializable()]
[XmlRoot(ElementName = "test", Namespace = "test:client")]
public class TestModel
{
    public TestModel()
    {
    }

    [XmlAttribute("name")]
    public string Name { get; set; }
    [XmlAttribute("type")]
    public string Id { get; set; }
}

我永远无法更改 xml。我想在朋友元素中列出内容。 请帮帮我!!

【问题讨论】:

    标签: c# xml serialization


    【解决方案1】:

    尝试以下:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Xml;
    using System.Xml.Serialization;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            const string FILENAME = @"c:\temp\test.xml";
            static void Main(string[] args)
            {
                XmlReader reader = XmlReader.Create(FILENAME);
                XmlSerializer serializer = new XmlSerializer(typeof(TestModel));
                TestModel testModel = (TestModel)serializer.Deserialize(reader);
            }
        }
        [XmlRoot(ElementName = "test", Namespace = "test:client")]
        public class TestModel
        {
    
            [XmlAttribute("name")]
            public string Name { get; set; }
            [XmlAttribute("type")]
            public string Id { get; set; }
    
            [XmlArray(ElementName = "friends", Namespace = "friends:test")]
            [XmlArrayItem("friend", Namespace = "")]
            public List<Friend> friends { get; set; }
        }
        public class Friend
        {
            [XmlText]
            public string text { get; set; }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-28
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 2010-12-06
      • 1970-01-01
      相关资源
      最近更新 更多