如何解决如何使用C#将模式匹配的XML元素序列化为列表
我的XML输入如下-
<?xml version="1.0"?>
-<INPUT>
<V0>10.0000</V0>
<V1>20.0000</V1>
<V2>30.0000</V2>
<V3>:0.0000</V3>
<V4>30.0000</V4>
<V5>0.0000</V5>
<V6>0.0000</V6>
<V7>0.0000</V7>
<V8>0.0000</V8>
<V9>0.0000</V9>
<V10>0.0000</V10>
<V11>50.0000</V11>
<V12>20.0000</V12>
<V13>60.0000</V13>
<V14>30.0000</V14>
<V15>0.0000</V15>
<V16>1.0000</V16>
-</INPUT>
我想将其序列化为以下C#类结构的对象-
class Input
{
List<V> variables;
}
因此,我想为具有模式V [0-9] +(例如V0,V1,V2等)的XML元素创建一个列表。该列表是有序列表,用于保留变量元素的索引。仅提及如果我们可以按预期成功地序列化所提到的XML,则该对象应具有16个项目的列表(因为有16个XML元素具有模式V [0-9] +)。实际的XML输入有数百个可变元素。
解决方法
使用xml linq:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
Input input = new Input();
XDocument doc = XDocument.Load(FILENAME);
input.variables = doc.Element("INPUT").Elements().Select(x => decimal.Parse((string)x)).ToList();
}
}
public class Input
{
public List<decimal> variables;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。