c# - 反序列化 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。我想在朋友元素中列出内容。请帮我!!
解决方案
尝试以下:
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; }
}
}
推荐阅读
- r - 如何将案例 ID 添加到列表中,直到它们的累积值达到 R 中的阈值?
- c# - 每 x 次移动一个游戏对象 x 次
- javascript - React 中的清除按钮清除输入但不重置数组元素
- r - 为什么这段代码有效?[R] [dplyr] [变异]
- python - 即使我使用 pip install 安装了本地包,Python 也会抛出 ModuleNotFoundError
- r - ggplot2 | 在条形图的堆栈中仅显示一个类别的数据值
- vega-lite - Vega-lite:根据选择自定义轴样式
- javascript - MS PowerPoint JavaScript API BETA - 如何使用 insertSlidesFromBase64(base64File, options) 插入新幻灯片?
- mysql - SQL:通过 I/O 数据透视表查询相关记录
- node.js - 尝试使用 GET 请求的正文发送 POST 请求