![](/img/trans.png)
[英]How to Read a particular Data from XML file and Write it to an Existing Excel Sheet using c#
[英]C# .Net - write data in xml by using existing structure/schema
我有一个API,可基于架构文件创建示例xml。 这是指向API的链接: http : //msdn.microsoft.com/zh-cn/library/aa302296.aspx
现在,假设生成的示例xml如下:
<Employee>
<Name>Bond</Name>
<Address>abc,unknown street</Address>
<phone>0000000000</phone>
<Employee>
我有一个包含数千个员工记录的员工数据库表。 我想要的是用上面创建的xml格式写那些记录(表也有很多非必需的列,所以不能使用dataset.writexml
)。
正确的做法是什么? 我是否应该根据第一条记录编辑第一个节点,然后将整个节点复制到相同的xml中,写入记录,然后重复该过程直到记录结束? 还是有更好的方法呢?
这是将对象序列化和反序列化为xml的示例。
using System;
using System.Xml.Serialization;
using System.IO;
namespace Test
{
[Serializable]
[XmlRoot("DocumentElement")]
public class Documentelement
{
[XmlElement]
public PartInfo[] PartInfo { get; set; }
}
public class PartInfo
{
[XmlElement]
public int ID { get; set; }
public string Name { get; set; }
public string PartNo { get; set; }
public int SerialNo { get; set; }
public string Parameter { get; set; }
public DateTime InstallDate { get; set; }
public DateTime InstallTill { get; set; }
}
public class Test
{
private PartInfo details_1()
{
PartInfo details = new PartInfo
{
ID = 0,
Name = "QVR",
PartNo = "A11",
SerialNo = 453,
Parameter = "C -11",
// This you should add as date time, I just used the string to parse your time that you showed in your example.
InstallDate = DateTime.Parse("2013-02-04T17:16:56.383+05:30"),
InstallTill = DateTime.Parse("2013-02-15T17:16:56.3830837+05:30")
};
return details;
}
private PartInfo details_2()
{
PartInfo details = new PartInfo
{
ID = 1,
Name = "EAFR",
PartNo = "B07",
SerialNo = 32,
Parameter = "B-16",
// This you should add as date time, I just used the string to parse your time that you showed in your example.
InstallDate = DateTime.Parse("2013-02-18T17:17:44.589+05:30"),
InstallTill = DateTime.Parse("2013-02-28T17:17:44.589+05:30")
};
return details;
}
public void setXmlValues()
{
Documentelement testOut = new Documentelement { PartInfo = new[] { details_1(), details_2() }};
xml_serialise(testOut);
Documentelement testIn = xml_deserialise();
int val = testIn.PartInfo[0].ID;
DateTime dt = testIn.PartInfo[0].InstallDate;
string shortTime = dt.ToShortTimeString();
}
private void xml_serialise(Documentelement test)
{
XmlSerializer ser = new XmlSerializer(typeof(Documentelement));
using (TextWriter writer = new StreamWriter("test.xml"))
{
ser.Serialize(writer, test);
}
}
private Documentelement xml_deserialise()
{
XmlSerializer ser = new XmlSerializer(typeof(Documentelement));
Documentelement test;
using (TextReader writer = new StreamReader("test.xml"))
{
test = (Documentelement)ser.Deserialize(writer);
}
return test;
}
}
}
一种方法是使用xsd.exe
(VS命令行工具之一)从示例XML生成架构,然后将xsd.exe
与该架构一起使用以生成C#类。 该类已准备好与序列化一起使用,因此您可以将数据转换为List<GeneratedClass>
,然后对其进行序列化 。 并不是说这是最好的方法,但是我在成功之前已经使用过它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.