C# 从xml填充列表集合
我有以下xsd并从中生成了一个.net类。我需要阅读xml文件并在.Net类中填充问题和答案。我还需要访问SubQuestionAnswer\Question和SubQuestionAnswer\Answer节点,并分别将其分配给qa.SubQuestions.SubQuestion和qa.SubQuestions.SubAnswer。有人能告诉我代码是否有效吗。循环通过xmlnodes和循环通过列表来分配节点值的逻辑 XSD文件C# 从xml填充列表集合,c#,xml,c#-4.0,xml-parsing,C#,Xml,C# 4.0,Xml Parsing,我有以下xsd并从中生成了一个.net类。我需要阅读xml文件并在.Net类中填充问题和答案。我还需要访问SubQuestionAnswer\Question和SubQuestionAnswer\Answer节点,并分别将其分配给qa.SubQuestions.SubQuestion和qa.SubQuestions.SubAnswer。有人能告诉我代码是否有效吗。循环通过xmlnodes和循环通过列表来分配节点值的逻辑 XSD文件 <xs:complexType name="Fatca"
<xs:complexType name="Fatca">
<xs:sequence>
<xs:element name="AccountNumber" type="xs:string"/>
<xs:element name="Questionnaire" type="FatcaQuestions" maxOccurs="unbounded" minOccurs="1"/>
<xs:element name="ContactDetails" type="ContactDetails"/>
<xs:element name="AccountDetails" type="AccountDetailsBasic" />
<xs:element name="Request" type="GeneralAccountId" />
</xs:sequence>
</xs:complexType>
<xs:complexType name="FatcaQuestions">
<xs:sequence>
<xs:element name="Question" type="xs:string" />
<xs:element name="Answer" type="xs:string" />
<xs:element name="SubQuestions" type="FatcaSubQuestions" maxOccurs="1" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="FatcaSubQuestions">
<xs:sequence>
<xs:element name="SubQuestion" type="xs:string" />
<xs:element name="SubAnswer" type="xs:string" />
</xs:sequence>
</xs:complexType>
下面是从这个xsd生成的类
public partial class Fatca
{
private string accountNumberField;
private List<FatcaQuestions> questionnaireField;
private ContactDetails contactDetailsField;
private AccountDetailsBasic accountDetailsField;
private GeneralAccountId requestField;
private static System.Xml.Serialization.XmlSerializer serializer;
public Fatca()
{
this.requestField = new GeneralAccountId();
this.accountDetailsField = new AccountDetailsBasic();
this.contactDetailsField = new ContactDetails();
this.questionnaireField = new List<FatcaQuestions>();
}
public string AccountNumber
{
get
{
return this.accountNumberField;
}
set
{
this.accountNumberField = value;
}
}
[System.Xml.Serialization.XmlElementAttribute("Questionnaire")]
public List<FatcaQuestions> Questionnaire
{
get
{
return this.questionnaireField;
}
set
{
this.questionnaireField = value;
}
}
public ContactDetails ContactDetails
{
get
{
return this.contactDetailsField;
}
set
{
this.contactDetailsField = value;
}
}
public AccountDetailsBasic AccountDetails
{
get
{
return this.accountDetailsField;
}
set
{
this.accountDetailsField = value;
}
}
public GeneralAccountId Request
{
get
{
return this.requestField;
}
set
{
this.requestField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer
{
get
{
if ((serializer == null))
{
serializer = new System.Xml.Serialization.XmlSerializer(typeof(Fatca));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current Fatca object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize()
{
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try
{
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally
{
if ((streamReader != null))
{
streamReader.Dispose();
}
if ((memoryStream != null))
{
memoryStream.Dispose();
}
}
}
public static bool Deserialize(string xml, out Fatca obj, out System.Exception exception)
{
exception = null;
obj = default(Fatca);
try
{
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex)
{
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out Fatca obj)
{
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static Fatca Deserialize(string xml)
{
System.IO.StringReader stringReader = null;
try
{
stringReader = new System.IO.StringReader(xml);
return ((Fatca)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally
{
if ((stringReader != null))
{
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current Fatca object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception)
{
exception = null;
try
{
SaveToFile(fileName);
return true;
}
catch (System.Exception e)
{
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName)
{
System.IO.StreamWriter streamWriter = null;
try
{
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally
{
if ((streamWriter != null))
{
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an Fatca object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output Fatca object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out Fatca obj, out System.Exception exception)
{
exception = null;
obj = default(Fatca);
try
{
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex)
{
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out Fatca obj)
{
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static Fatca LoadFromFile(string fileName)
{
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try
{
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally
{
if ((file != null))
{
file.Dispose();
}
if ((sr != null))
{
sr.Dispose();
}
}
}
#endregion
}
public partial class FatcaQuestions
{
private string questionField;
private string answerField;
private FatcaSubQuestions subQuestionsField;
private static System.Xml.Serialization.XmlSerializer serializer;
public FatcaQuestions()
{
this.subQuestionsField = new FatcaSubQuestions();
}
public string Question
{
get
{
return this.questionField;
}
set
{
this.questionField = value;
}
}
public string Answer
{
get
{
return this.answerField;
}
set
{
this.answerField = value;
}
}
public FatcaSubQuestions SubQuestions
{
get
{
return this.subQuestionsField;
}
set
{
this.subQuestionsField = value;
}
}
private static System.Xml.Serialization.XmlSerializer Serializer
{
get
{
if ((serializer == null))
{
serializer = new System.Xml.Serialization.XmlSerializer(typeof(FatcaQuestions));
}
return serializer;
}
}
#region Serialize/Deserialize
/// <summary>
/// Serializes current FatcaQuestions object into an XML document
/// </summary>
/// <returns>string XML value</returns>
public virtual string Serialize()
{
System.IO.StreamReader streamReader = null;
System.IO.MemoryStream memoryStream = null;
try
{
memoryStream = new System.IO.MemoryStream();
Serializer.Serialize(memoryStream, this);
memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
streamReader = new System.IO.StreamReader(memoryStream);
return streamReader.ReadToEnd();
}
finally
{
if ((streamReader != null))
{
streamReader.Dispose();
}
if ((memoryStream != null))
{
memoryStream.Dispose();
}
}
}
/// <summary>
/// Deserializes workflow markup into an FatcaQuestions object
/// </summary>
/// <param name="xml">string workflow markup to deserialize</param>
/// <param name="obj">Output FatcaQuestions object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool Deserialize(string xml, out FatcaQuestions obj, out System.Exception exception)
{
exception = null;
obj = default(FatcaQuestions);
try
{
obj = Deserialize(xml);
return true;
}
catch (System.Exception ex)
{
exception = ex;
return false;
}
}
public static bool Deserialize(string xml, out FatcaQuestions obj)
{
System.Exception exception = null;
return Deserialize(xml, out obj, out exception);
}
public static FatcaQuestions Deserialize(string xml)
{
System.IO.StringReader stringReader = null;
try
{
stringReader = new System.IO.StringReader(xml);
return ((FatcaQuestions)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader))));
}
finally
{
if ((stringReader != null))
{
stringReader.Dispose();
}
}
}
/// <summary>
/// Serializes current FatcaQuestions object into file
/// </summary>
/// <param name="fileName">full path of outupt xml file</param>
/// <param name="exception">output Exception value if failed</param>
/// <returns>true if can serialize and save into file; otherwise, false</returns>
public virtual bool SaveToFile(string fileName, out System.Exception exception)
{
exception = null;
try
{
SaveToFile(fileName);
return true;
}
catch (System.Exception e)
{
exception = e;
return false;
}
}
public virtual void SaveToFile(string fileName)
{
System.IO.StreamWriter streamWriter = null;
try
{
string xmlString = Serialize();
System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName);
streamWriter = xmlFile.CreateText();
streamWriter.WriteLine(xmlString);
streamWriter.Close();
}
finally
{
if ((streamWriter != null))
{
streamWriter.Dispose();
}
}
}
/// <summary>
/// Deserializes xml markup from file into an FatcaQuestions object
/// </summary>
/// <param name="fileName">string xml file to load and deserialize</param>
/// <param name="obj">Output FatcaQuestions object</param>
/// <param name="exception">output Exception value if deserialize failed</param>
/// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns>
public static bool LoadFromFile(string fileName, out FatcaQuestions obj, out System.Exception exception)
{
exception = null;
obj = default(FatcaQuestions);
try
{
obj = LoadFromFile(fileName);
return true;
}
catch (System.Exception ex)
{
exception = ex;
return false;
}
}
public static bool LoadFromFile(string fileName, out FatcaQuestions obj)
{
System.Exception exception = null;
return LoadFromFile(fileName, out obj, out exception);
}
public static FatcaQuestions LoadFromFile(string fileName)
{
System.IO.FileStream file = null;
System.IO.StreamReader sr = null;
try
{
file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read);
sr = new System.IO.StreamReader(file);
string xmlString = sr.ReadToEnd();
sr.Close();
file.Close();
return Deserialize(xmlString);
}
finally
{
if ((file != null))
{
file.Dispose();
}
if ((sr != null))
{
sr.Dispose();
}
}
}
#endregion
}
公共部分类Fatca
{
私有字符串accountNumberField;
私人名单问题;
私人联系人详情联系人详情字段;
私人账户详情基本账户详情字段;
私有GeneralAccounted请求字段;
私有静态System.Xml.Serialization.XmlSerializer序列化程序;
公共Fatca()
{
this.requestField=新的GeneralAccounted();
this.accountDetailsField=新AccountDetailsBasic();
this.ContactDetails字段=新的ContactDetails();
this.questionnaireField=新列表();
}
公共字符串帐号
{
得到
{
返回此.accountNumberField;
}
设置
{
this.accountNumberField=值;
}
}
[System.Xml.Serialization.xmlementAttribute(“调查问卷”)]
公众名单问卷
{
得到
{
返回此.questionnaireField;
}
设置
{
this.questionnaireField=值;
}
}
公众联络资料联络资料
{
得到
{
返回此.contactDetails字段;
}
设置
{
this.contactDetails字段=值;
}
}
公共帐户详细信息基本帐户详细信息
{
得到
{
返回此.accountDetails字段;
}
设置
{
this.accountDetailsField=值;
}
}
公共一般帐户请求
{
得到
{
返回此.requestField;
}
设置
{
this.requestField=值;
}
}
私有静态System.Xml.Serialization.XmlSerializer序列化程序
{
得到
{
if((序列化程序==null))
{
serializer=new System.Xml.Serialization.XmlSerializer(typeof(Fatca));
}
返回序列化程序;
}
}
#区域序列化/反序列化
///
///将当前Fatca对象序列化为XML文档
///
///字符串XML值
公共虚拟字符串序列化()
{
System.IO.StreamReader StreamReader=null;
System.IO.MemoryStream MemoryStream=null;
尝试
{
memoryStream=新系统.IO.memoryStream();
Serializer.Serialize(memoryStream,this);
memoryStream.Seek(0,System.IO.SeekOrigin.Begin);
streamReader=新的System.IO.streamReader(memoryStream);
返回streamReader.ReadToEnd();
}
最后
{
如果((streamReader!=null))
{
streamReader.Dispose();
}
如果((memoryStream!=null))
{
memoryStream.Dispose();
}
}
}
公共静态布尔反序列化(字符串xml、out Fatca obj、out System.Exception)
{
异常=空;
obj=违约(Fatca);
尝试
{
obj=反序列化(xml);
返回true;
}
catch(System.Exception-ex)
{
例外=例外;
返回false;
}
}
公共静态布尔反序列化(字符串xml,输出Fatca obj)
{
System.Exception=null;
返回反序列化(xml、out obj、out异常);
}
公共静态Fatca反序列化(字符串xml)
{
System.IO.StringReader StringReader=null;
尝试
{
stringReader=new System.IO.stringReader(xml);
return((Fatca)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)));
}
最后
{
如果((stringReader!=null))
{
stringReader.Dispose();
}
}
}
///
///将当前Fatca对象序列化为文件
///
///outupt xml文件的完整路径
///如果失败,则输出异常值
///如果可以序列化并保存到文件中,则为true;oth
XmlDocument xmlDocument = new XmlDocument();
var fataQuestionnaire = @"<?xml version=""1.0"" encoding=""UTF-16""?>
<FatcaQuestionnaire xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<QuestionAnswers>
<QuestionAnswer>
<Question>What is your source of wealth?</Question>
<Answer>I am italian </Answer>
</QuestionAnswer>
<QuestionAnswer>
<Question>What is your occupation and name of employer?</Question>
<Answer>Bestinvest</Answer>
</QuestionAnswer>
<QuestionAnswer>
<Question>Do you have a business or residence in?</Question>
<Answer>Yes</Answer>
</QuestionAnswer>
<QuestionAnswer>
<Question>How long have you lived outside of Albania</Question>
<Answer>5 years</Answer>
</QuestionAnswer>
<QuestionAnswer>
<Question>Do you return to Albania on a regular basis</Question>
<Answer>Yes</Answer>
<SubQuestionAnswer>
<Question>How frequently?</Question>
<Answer>every year</Answer>
</SubQuestionAnswer>
</QuestionAnswer>
<QuestionAnswer>
<Question>Do you have family in Albania?</Question>
<Answer>Yes</Answer>
<SubQuestionAnswer>
<Question>Family relationship?</Question>
<Answer>My parents lives there</Answer>
</SubQuestionAnswer>
</QuestionAnswer>
<QuestionAnswer>
<Question>Are you connected to the government of Albania?</Question>
<Answer>Yes</Answer>
<SubQuestionAnswer>
<Question>Nature of association</Question>
<Answer>I was an ex minister</Answer>
</SubQuestionAnswer>
</QuestionAnswer>
<QuestionAnswer>
<Question>Do you send or receive money from Albania?</Question>
<Answer>Yes</Answer>
<SubQuestionAnswer>
<Question>How often and why?</Question>
<Answer>Every month for my parents to live with.</Answer>
</SubQuestionAnswer>
</QuestionAnswer>
</QuestionAnswers>
</FatcaQuestionnaire>";
XmlTextReader reader = new XmlTextReader(new StringReader(fataQuestionnaire));
xmlDocument.Load(reader);
XmlElement xmlRoot = xmlDocument.DocumentElement;
if (xmlRoot != null)
{
XmlNodeList xnlNodes = xmlRoot.SelectNodes("/FatcaQuestionnaire/QuestionAnswers/QuestionAnswer");
foreach (XmlNode xndNode in xnlNodes)
{
foreach (var qa in fatca.Questionnaire)
{
if (xndNode["Question"] != null)
qa.Question = xndNode["Question"].InnerText;
if (xndNode["Answer"] != null)
qa.Answer = xndNode["Answer"].InnerText;
}
}