C# 将XML文档转换为对象
我已经看过好几篇关于这类问题的帖子,但我似乎无法让它起作用 我得到了这个XML文件(全部): 下面是我尝试解析的C#代码:C# 将XML文档转换为对象,c#,xml,converter,xmldocument,C#,Xml,Converter,Xmldocument,我已经看过好几篇关于这类问题的帖子,但我似乎无法让它起作用 我得到了这个XML文件(全部): 下面是我尝试解析的C#代码: const string hardCodedConfigFilePath = @"C:\Program Files (x86)\MyApp.exe.config"; string xmlDocumentText = File.ReadAllText(hardCodedConfigFilePath); XmlDocument doc = new XmlDocument();
const string hardCodedConfigFilePath = @"C:\Program Files (x86)\MyApp.exe.config";
string xmlDocumentText = File.ReadAllText(hardCodedConfigFilePath);
XmlDocument doc = new XmlDocument();
doc.LoadXml(xmlDocumentText);
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement["StationsSection"]);
string firstStationConfiguration = doc.DocumentElement["StationsSection"].ChildNodes[0].InnerXml; //here's the chunk that contains my data
XmlSerializer ser = new XmlSerializer(typeof(StationConfiguration));
object obj = ser.Deserialize(reader);
名为firstStationConfiguration
的字符串包含以下内容:
<add Comment="My comment goes here"
DestinationFolderPath="C:\TestInstallation"
FtpHostname="ftp://upload.servername.com/"
FtpFolderPath="myFolderPath/"
FtpUsername="myUsername"
FtpPassword="abcdefg" FtpTimeoutInSeconds="20" />
执行最后一个C#行时,将抛出:
“System.InvalidOperationException”类型的未处理异常
在System.Xml.dll中发生其他信息:出现错误
在XML文档中
请。。。如何将
站点
节点(可能包含多个节点)转换为C#对象?无法在有限的时间内确定这一点。但也许你可以在这方面努力;似乎该节点被称为Stations,因此它正在寻找Stations类而不是StationConfiguration。但我还没有将属性作为XML属性部分
void Main()
{
const string hardCodedConfigFilePath = @"\\ai-vmdc1\RedirectedFolders\jlambert\Documents\MyApp.exe.config";
string xmlDocumentText = File.ReadAllText(hardCodedConfigFilePath);
XmlDocument doc = new XmlDocument();
//doc.Schemas.Add(, xsdPath
//Console.WriteLine(xmlDocumentText);
doc.LoadXml(xmlDocumentText);
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement["StationsSection"]);
string firstStationConfiguration = doc.DocumentElement["StationsSection"].ChildNodes[0].OuterXml;//.InnerXml; //here's the chunk that contains my data
XmlSerializer ser = new XmlSerializer(typeof(Stations));
// Console.WriteLine(xmlDocumentText);
//object obj = ser.Deserialize(reader);
Console.WriteLine(firstStationConfiguration);
using (StringReader stringReader = new StringReader(firstStationConfiguration))
{
Stations sc = (Stations)ser.Deserialize(stringReader);
Console.WriteLine(sc.Comment);
Console.WriteLine(sc.FtpUsername);
Console.WriteLine(sc.FtpPassword);
Console.WriteLine(sc.DestinationFolderPath);
}
}
// Define other methods and classes here
[Serializable]
public class Stations
{
[XmlAttribute("Comment")]
public string Comment { get; set;}
[XmlAttribute]
public string FtpUsername { get; set;}
[XmlAttribute]
public string FtpPassword { get; set;}
[XmlAttribute]
public string DestinationFolderPath { get; set;}
}
不能在有限的时间内完全解决这个问题。但也许你可以在这方面努力;似乎该节点被称为Stations,因此它正在寻找Stations类而不是StationConfiguration。但我还没有将属性作为XML属性部分
void Main()
{
const string hardCodedConfigFilePath = @"\\ai-vmdc1\RedirectedFolders\jlambert\Documents\MyApp.exe.config";
string xmlDocumentText = File.ReadAllText(hardCodedConfigFilePath);
XmlDocument doc = new XmlDocument();
//doc.Schemas.Add(, xsdPath
//Console.WriteLine(xmlDocumentText);
doc.LoadXml(xmlDocumentText);
XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement["StationsSection"]);
string firstStationConfiguration = doc.DocumentElement["StationsSection"].ChildNodes[0].OuterXml;//.InnerXml; //here's the chunk that contains my data
XmlSerializer ser = new XmlSerializer(typeof(Stations));
// Console.WriteLine(xmlDocumentText);
//object obj = ser.Deserialize(reader);
Console.WriteLine(firstStationConfiguration);
using (StringReader stringReader = new StringReader(firstStationConfiguration))
{
Stations sc = (Stations)ser.Deserialize(stringReader);
Console.WriteLine(sc.Comment);
Console.WriteLine(sc.FtpUsername);
Console.WriteLine(sc.FtpPassword);
Console.WriteLine(sc.DestinationFolderPath);
}
}
// Define other methods and classes here
[Serializable]
public class Stations
{
[XmlAttribute("Comment")]
public string Comment { get; set;}
[XmlAttribute]
public string FtpUsername { get; set;}
[XmlAttribute]
public string FtpPassword { get; set;}
[XmlAttribute]
public string DestinationFolderPath { get; set;}
}
试试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
Configuration config = new Configuration() {
configSections = new ConfigSections() {
section = new List<Section>() {
new Section() { name = "StationsSection", type="AcmeTV_EcFtpClient.StationConfigurationSection, AcmeTV_EcFtpClient"}
}
},
stationsSection = new StationsSection() {
station = new List<Station>() {
new Station() {
add = new StationAdd() {
comment ="My comment goes here",
destinationFolderPath = "C:\\TestInstallation",
ftpHostname = "ftp://upload.servername.com/",
ftpFolderPath = "myFolderPath/",
ftpUsername = "myUserName",
ftpPassword = "myFtpPassword",
ftpTimeoutInSeconds = 20
}
}
}
},
startup = new Startup() {
supportedRuntime = new SupportedRuntime() {
version = "v2.0.50727"
}
},
appSettings = new AppSettings() {
appSettingAdd = new List<AppSettingAdd>() {
new AppSettingAdd() { key= "NameOfService", value="AcmeECClient"},
new AppSettingAdd() { key="PollingFrequencyInSeconds", value="60"}
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
StreamWriter writer = new StreamWriter(FILENAME);
serializer.Serialize(writer, config);
writer.Flush();
writer.Close();
writer.Dispose();
XmlSerializer xs = new XmlSerializer(typeof(Configuration));
XmlTextReader reader = new XmlTextReader(FILENAME);
Configuration newConfig = (Configuration)xs.Deserialize(reader);
}
}
[XmlRoot("configuration")]
public class Configuration
{
[XmlElement("configSections")]
public ConfigSections configSections { get; set; }
[XmlElement("StationsSection")]
public StationsSection stationsSection { get; set; }
[XmlElement("startup")]
public Startup startup { get; set; }
[XmlElement("appSettings")]
public AppSettings appSettings { get; set; }
}
[XmlRoot("configSections")]
public class ConfigSections
{
[XmlElement("section")]
public List<Section> section { get; set; }
}
[XmlRoot("section")]
public class Section
{
[XmlAttribute("name")]
public string name { get; set;}
[XmlAttribute("type")]
public string type { get; set; }
}
[XmlRoot("StationsSection")]
public class StationsSection
{
[XmlElement("Stations")]
public List<Station> station { get; set; }
}
[XmlRoot("Stations")]
public class Station
{
[XmlElement("add")]
public StationAdd add { get; set; }
}
[XmlRoot("add")]
public class StationAdd
{
[XmlAttribute("Comment")]
public string comment { get; set; }
[XmlAttribute("DestinationFolderPath")]
public string destinationFolderPath { get; set; }
[XmlAttribute("FtpHostname")]
public string ftpHostname { get; set; }
[XmlAttribute("FtpFolderPath")]
public string ftpFolderPath { get; set; }
[XmlAttribute("FtpUsername")]
public string ftpUsername { get; set; }
[XmlAttribute("FtpPassword")]
public string ftpPassword { get; set; }
[XmlAttribute("FtpTimeoutInSeconds")]
public int ftpTimeoutInSeconds { get; set; }
}
[XmlRoot("startup")]
public class Startup
{
[XmlElement("supportedRuntime")]
public SupportedRuntime supportedRuntime { get; set; }
}
[XmlRoot("supportedRuntime")]
public class SupportedRuntime
{
[XmlAttribute("version")]
public string version { get; set; }
}
[XmlRoot("appSettings")]
public class AppSettings
{
[XmlElement("add")]
public List<AppSettingAdd> appSettingAdd { get; set;}
}
[XmlRoot("add")]
public class AppSettingAdd
{
[XmlAttribute("key")]
public string key { get; set; }
[XmlAttribute("value")]
public string value { get; set; }
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Xml;
使用System.Xml.Serialization;
使用System.IO;
使用System.Text.RegularExpressions;
命名空间控制台应用程序1
{
班级计划
{
常量字符串文件名=@“c:\temp\test.xml”;
静态void Main(字符串[]参数)
{
配置配置=新配置(){
configSections=新的configSections(){
节=新列表(){
新建节(){name=“stationSection”,type=“AcmeTV_EcFtpClient.stationConfiguration节,AcmeTV_EcFtpClient”}
}
},
StationSection=新建StationSection(){
站点=新列表(){
新电台(){
添加=新StationAdd(){
comment=“我的评论在这里”,
destinationFolderPath=“C:\\TestInstallation”,
ftpHostname=”ftp://upload.servername.com/",
ftpFolderPath=“myFolderPath/”,
ftpUsername=“myUserName”,
ftpPassword=“myFtpPassword”,
ftpTimeOutines=20秒
}
}
}
},
startup=新启动(){
supportedRuntime=新的supportedRuntime(){
version=“v2.0.50727”
}
},
appSettings=新的appSettings(){
appSettingAdd=新列表(){
新建appsetingadd(){key=“NameOfService”,value=“AcmeECClient”},
新建AppSettingAdd(){key=“PollingFrequencyInSeconds”,value=“60”}
}
}
};
XmlSerializer serializer=新的XmlSerializer(类型(配置));
StreamWriter writer=新的StreamWriter(文件名);
serializer.Serialize(writer,config);
writer.Flush();
writer.Close();
writer.Dispose();
XmlSerializer xs=新的XmlSerializer(类型(配置));
XmlTextReader=新的XmlTextReader(文件名);
配置newConfig=(配置)xs.Deserialize(读取器);
}
}
[XmlRoot(“配置”)]
公共类配置
{
[XmlElement(“配置节”)]
公共配置节配置节{get;set;}
[XmlElement(“StationSection”)]
公共站点SECTIONSECTIONSECTION{get;set;}
[XmlElement(“启动”)]
公共启动启动{get;set;}
[XmlElement(“appSettings”)]
公共AppSettings AppSettings{get;set;}
}
[XmlRoot(“配置节”)]
公共类配置部分
{
[XmlElement(“节”)]
公共列表节{get;set;}
}
[XmlRoot(“节”)]
公共课组
{
[XmlAttribute(“名称”)]
公共字符串名称{get;set;}
[XmlAttribute(“类型”)]
公共字符串类型{get;set;}
}
[XmlRoot(“StationSection”)]
公共课站组
{
[XmlElement(“站点”)]
公共列表站{get;set;}
}
[XmlRoot(“站点”)]
公营电台
{
[XmlElement(“添加”)]
公共站添加{get;set;}
}
[XmlRoot(“添加”)]
公务舱
{
[XmlAttribute(“注释”)]
公共字符串注释{get;set;}
[XmlAttribute(“DestinationFolderPath”)]
公共字符串destinationFolderPath{get;set;}
[XmlAttribute(“FtpHostname”)]
公共字符串ftpHostname{get;set;}
[XmlAttribute(“FtpFolderPath”)]
公共字符串ftpFolderPath{get;set;}
[XmlAttribute(“FtpUsername”)]
公共字符串ftpUsername{get;set;}
[xmldattribute(“FtpPassword”)]
公共字符串ftpPassword{get;set;}
[XmlAttribute(“ftpTimeOutingSeconds”)]
public int ftpTimeOutingSeconds{get;set;}
}
[XmlRoot(“启动”)]
公营创业
{
[XmlElement(“supportedRuntime”)]
公共支持的运行时间支持的运行时间{get;set;}
}
[XmlRoot(“supportedRuntime”)]
公共类支持的运行时间
{
[XmlAttribute(“版本”)]
公共字符串版本{get;set;}
}
[XmlRoot(“appSettings”)]
公共类应用程序设置
{
[XmlElement(“添加”)]
公共列表appSettingAdd{get;set;}
}
[XmlRoot(“添加”)]
公共类AppSettingAdd
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
Configuration config = new Configuration() {
configSections = new ConfigSections() {
section = new List<Section>() {
new Section() { name = "StationsSection", type="AcmeTV_EcFtpClient.StationConfigurationSection, AcmeTV_EcFtpClient"}
}
},
stationsSection = new StationsSection() {
station = new List<Station>() {
new Station() {
add = new StationAdd() {
comment ="My comment goes here",
destinationFolderPath = "C:\\TestInstallation",
ftpHostname = "ftp://upload.servername.com/",
ftpFolderPath = "myFolderPath/",
ftpUsername = "myUserName",
ftpPassword = "myFtpPassword",
ftpTimeoutInSeconds = 20
}
}
}
},
startup = new Startup() {
supportedRuntime = new SupportedRuntime() {
version = "v2.0.50727"
}
},
appSettings = new AppSettings() {
appSettingAdd = new List<AppSettingAdd>() {
new AppSettingAdd() { key= "NameOfService", value="AcmeECClient"},
new AppSettingAdd() { key="PollingFrequencyInSeconds", value="60"}
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
StreamWriter writer = new StreamWriter(FILENAME);
serializer.Serialize(writer, config);
writer.Flush();
writer.Close();
writer.Dispose();
XmlSerializer xs = new XmlSerializer(typeof(Configuration));
XmlTextReader reader = new XmlTextReader(FILENAME);
Configuration newConfig = (Configuration)xs.Deserialize(reader);
}
}
[XmlRoot("configuration")]
public class Configuration
{
[XmlElement("configSections")]
public ConfigSections configSections { get; set; }
[XmlElement("StationsSection")]
public StationsSection stationsSection { get; set; }
[XmlElement("startup")]
public Startup startup { get; set; }
[XmlElement("appSettings")]
public AppSettings appSettings { get; set; }
}
[XmlRoot("configSections")]
public class ConfigSections
{
[XmlElement("section")]
public List<Section> section { get; set; }
}
[XmlRoot("section")]
public class Section
{
[XmlAttribute("name")]
public string name { get; set;}
[XmlAttribute("type")]
public string type { get; set; }
}
[XmlRoot("StationsSection")]
public class StationsSection
{
[XmlElement("Stations")]
public List<Station> station { get; set; }
}
[XmlRoot("Stations")]
public class Station
{
[XmlElement("add")]
public StationAdd add { get; set; }
}
[XmlRoot("add")]
public class StationAdd
{
[XmlAttribute("Comment")]
public string comment { get; set; }
[XmlAttribute("DestinationFolderPath")]
public string destinationFolderPath { get; set; }
[XmlAttribute("FtpHostname")]
public string ftpHostname { get; set; }
[XmlAttribute("FtpFolderPath")]
public string ftpFolderPath { get; set; }
[XmlAttribute("FtpUsername")]
public string ftpUsername { get; set; }
[XmlAttribute("FtpPassword")]
public string ftpPassword { get; set; }
[XmlAttribute("FtpTimeoutInSeconds")]
public int ftpTimeoutInSeconds { get; set; }
}
[XmlRoot("startup")]
public class Startup
{
[XmlElement("supportedRuntime")]
public SupportedRuntime supportedRuntime { get; set; }
}
[XmlRoot("supportedRuntime")]
public class SupportedRuntime
{
[XmlAttribute("version")]
public string version { get; set; }
}
[XmlRoot("appSettings")]
public class AppSettings
{
[XmlElement("add")]
public List<AppSettingAdd> appSettingAdd { get; set;}
}
[XmlRoot("add")]
public class AppSettingAdd
{
[XmlAttribute("key")]
public string key { get; set; }
[XmlAttribute("value")]
public string value { get; set; }
}
}
public class Stations
{
[XmlElement(ElementName = "add", Namespace = "")]
public StationConfiguration StationConfiguration { get; set; }
}
[XmlType(AnonymousType = true, Namespace = "")]
public class StationConfiguration
{
readonly Regex OnlyAlphaNumericWithNoSpaces = new Regex("^[a-zA-Z0-9]*$");
public StationConfiguration() { }
public StationConfiguration(string comment, string ftpUsername, string ftpPassword, string destinationFolderPath)
{
Comment = comment;
FtpUsername = ftpUsername;
FtpPassword = ftpPassword;
DestinationFolderPath = destinationFolderPath;
}
public bool IsValidStation()
{
return OnlyAlphaNumericWithNoSpaces.IsMatch(Comment);
}
public bool IsValidUsername()
{
return OnlyAlphaNumericWithNoSpaces.IsMatch(FtpUsername);
}
public bool IsValidPassword()
{
return FtpPassword.Contains(' ') == false;
}
public bool IsValidFolderPath()
{
return Directory.Exists(DestinationFolderPath);
}
private string _comment;
[XmlAttribute]
public string Comment
{
get
{
return _comment;
}
set
{
_comment = value.ToUpper();
}
}
[XmlAttribute]
public string FtpUsername { get; set; }
[XmlAttribute]
public string FtpPassword { get; set; }
[XmlAttribute]
public string DestinationFolderPath { get; set; }
}
class Program
{
private static void Main(string[] args)
{
const string hardCodedConfigFilePath = @"test.xml";
sol1(hardCodedConfigFilePath);
sol2(hardCodedConfigFilePath);
sol3(hardCodedConfigFilePath);
}
public static void sol1(string hardCodedConfigFilePath)
{
string xmlDocumentText = File.ReadAllText(hardCodedConfigFilePath);
var doc = new XmlDocument();
doc.LoadXml(xmlDocumentText);
var docElem = new XmlDocument();
docElem.CreateXmlDeclaration("1.0", "utf-8", "yes");
var node = doc.DocumentElement["StationsSection"];
//Create a document fragment.
var docFrag = docElem.CreateDocumentFragment();
//Set the contents of the document fragment.
docFrag.InnerXml = node.InnerXml;
//Add the document fragment to the
// document.
docElem.AppendChild(docFrag);
var reader = new XmlNodeReader(docElem);
var ser = new XmlSerializer(typeof(Stations));
object obj = ser.Deserialize(reader);
}
public static void sol2(string hardCodedConfigFilePath)
{
string xmlDocumentText = File.ReadAllText(hardCodedConfigFilePath);
var doc = new XmlDocument();
doc.LoadXml(xmlDocumentText);
var attr = doc.DocumentElement["StationsSection"].ChildNodes[0].ChildNodes[0].Attributes;
// Check that attributes exist ...
var stationConfiguration = new StationConfiguration(attr["Comment"].Value
, attr["FtpUsername"].Value
, attr["FtpPassword"].Value
, attr["DestinationFolderPath"].Value);
}
public static void sol3(string hardCodedConfigFilePath)
{
var xdoc = XElement.Load(hardCodedConfigFilePath);
var config = xdoc.Descendants("Stations").Elements("add").FirstOrDefault();
// Check that attributes exist ...
var stationConfiguration = new StationConfiguration(config.Attribute("Comment").Value
, config.Attribute("FtpUsername").Value
, config.Attribute("FtpPassword").Value
, config.Attribute("DestinationFolderPath").Value);
}