首页 > 解决方案 > 反序列化 XML 不工作包含 xmlns

问题描述

这是我的 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#xmlserialization

解决方案


尝试以下:

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; }
    }
}

推荐阅读