我有以下XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<TestConfiguration xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Barcode>MB-B3-00</Barcode>
<TestSuites>
<Test>USB A Slave Port</Test>
<Test>USB B Host Port</Test>
</TestSuites>
</TestConfiguration>
我想将其反序列化为以下类:
public class TestConfiguration
{
private string _barcode;
private string[] _testSuites;
private string[] _testcase;
//Product barcode
public string Barcode
{
get{return this._barcode;}
set{this._barcode = value;}
}
//Test suites
[System.Xml.Serialization.XmlArrayItemAttribute("Test", IsNullable = false)]
public string[] Testsuites
{
get{return this._testSuites;}
set{this._testSuites = value;}
}
//individual test
[System.Xml.Serialization.XmlTextAttribute()]
public string[] Testcase
{
get{return this._testcase;}
set{this._testcase = value;}
}
}
我的反序列化代码是:
XmlSerializer serializer = new XmlSerializer(typeof(TestConfiguration));
StreamReader reader = new StreamReader(filename);
TestConfiguration _testConfig = (TestConfiguration)serializer.Deserialize(reader);
reader.Close();
但是,_testConfig
对象仅包含条形码值,属性Testcase
和TestSuites
为空。有什么建议吗?
答案 0 :(得分:1)
你非常接近。您的商家名称Testsuites
与<{1}}元素的名称不匹配 - 字母<TestSuites>
的大小写不同,{{ 3}}
要修复此问题,请重命名该媒体资源,或使用正确的XML Tags are Case Sensitive附加XmlArrayAttribute
:
S
答案 1 :(得分:0)
试试这个。你可以删除标签并拥有一个just元素数组。我可以告诉你如何。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XmlSerializer serializer = new XmlSerializer(typeof(TestConfiguration));
StreamReader reader = new StreamReader(FILENAME);
TestConfiguration _testConfig = (TestConfiguration)serializer.Deserialize(reader);
reader.Close();
}
}
[XmlRoot("TestConfiguration")]
public class TestConfiguration
{
private string _barcode;
private string[] _testSuites;
private string[] _testcase;
//Product barcode
[XmlElement("Barcode")]
public string Barcode { get; set; }
//Test suites
[XmlElement("TestSuites")]
public TestSuites testSuites { get; set; }
}
//individual test
[XmlRoot("TestSuites")]
public class TestSuites
{
[XmlElement("Test")]
public List<string> test {get;set;}
}
}