将XML导入类属性

时间:2013-02-27 13:25:29

标签: c# xml winforms import

我有这种格式的XML:

<?xml version="1.0" standalone="yes"?>
<DocumentElement>
<Session>
<bIsImages>False</bIsImages>
<bIsPlayMedia>False</bIsPlayMedia>
<bIsSubject>False</bIsSubject>
<bIsVideo>False</bIsVideo>
<dtCreDate>2012-07-23</dtCreDate>
<dtSes_Date1>2001-01-01</dtSes_Date1>
<dtSes_Date2>2001-01-01</dtSes_Date2>
<dtSes_Date3>2001-01-01</dtSes_Date3>
<nClient_ID>32</nClient_ID>
<nDelay>32</nDelay>
<nImage_ID>32</nImage_ID>
<nOperator_ID>32</nOperator_ID>
<nSession_ID>32</nSession_ID>
<nVitality>32</nVitality>
<strDescr>qi stagnatie abq</strDescr>
<strMediaPath></strMediaPath>
<strName>qi stagnatie abq</strName>
<strPrimCause></strPrimCause>
<strSubjectPath>IDF_Eric duBosc.JPG</strSubjectPath>
</Session>
<SessionProgramData>
</SessionProgramData><SessionSubProgramData>
</SessionSubProgramData><SessionTuningData>
<SessionTuning>
    <SessionTuning_ID>332</SessionTuning_ID>
    <Session_ID>33</Session_ID>
    <Tuning>Brjesh</Tuning>
    <TuningDescr>Brijesh Desc</TuningDescr>
    <TuningIsNegative>false</TuningIsNegative>
    <TuningAddInfo>33</TuningAddInfo>
    <Amp>4.8</Amp>
    <Amp2 />
    <Amp3 />
    <Amp4 />
    <Amp5 />
    <Amp6 />
    <TunFreq>Brjesh</TunFreq>
    <TunFreq2 />
    <TunFreq3 />
    <TunFreq4 />
    <TunFreq5 />
    <TunFreq6 />
    <Revision2>false</Revision2>
    <Revision3>false</Revision3>
    <Revision4>false</Revision4>
    <Revision5>false</Revision5>
    <Revision6>false</Revision6>
    <AlreadyBalanced>false</AlreadyBalanced>
    <ImagePath>E:\Live Projects with Latest Source Code\SE-5\SE-5-Latest-04March11-Multilanguage-Chinese\SE-5\bin\Release\Images\</ImagePath>
    <Amp7 />
    <TunFreq7 />
    <Revision7>0</Revision7>
    <Description>Brijesh Note</Description>
    <TunRevDate>2013-02-20T18:08:48+05:30</TunRevDate>
    <TunRevDate2>2013-02-20T18:08:48+05:30</TunRevDate2>
    <TunRevDate3>2013-02-20T18:08:48+05:30</TunRevDate3>
    <TunRevDate4>2013-02-20T18:08:48+05:30</TunRevDate4>
    <TunRevDate5>2013-02-20T18:08:48+05:30</TunRevDate5>
    <TunRevDate6>2013-02-20T18:08:48+05:30</TunRevDate6>
    <TunRevDate7>2013-02-20T18:08:48+05:30</TunRevDate7>
    <Tuning_ID>20568</Tuning_ID>
</SessionTuning>
....So on
<SessionTuning>
    .....
    .....
</SessionTuning>

</SessionTuningData>
<Client>
<nClient_ID>32</nClient_ID>
<strAddress></strAddress>
<strCity></strCity>
<strCountry></strCountry>
<strFirstName>Eric</strFirstName>
<strImage>IDF_Eric duBosc.JPG</strImage>
<strLastName>Bosc</strLastName>
<strMI>du</strMI>
<strNote>ikke</strNote>
<strPhoneNum></strPhoneNum>
<strPostalCode></strPostalCode>
<strState></strState>
<strWorkPhone></strWorkPhone>
</Client>
<SE-5 />
</DocumentElement>

使用多个SessionTuning,现在我想在我的String Array中导入这个XML。

我现有的代码:

public static clsSessionTuningData[] GetSessionTuningFromXMLFile(string FileName)
        {
            try
            {

                StreamReader objReader = new StreamReader(FileName);
                string strData = objReader.ReadToEnd();
                objReader.Close();

                int nStart = 0, nEnd = 0;
                nStart = strData.IndexOf("<SessionTuningData>");
                nEnd = strData.IndexOf("</SessionTuningData>");
                if (nStart > 0 && nEnd > 0)
                {

                    nStart = nStart + "<SessionTuningData>".Length;
                    nEnd = nEnd + "</SessionTuningData>".Length;
                    strData = strData.Substring(nStart + 1, nEnd - nStart - 1);
                    string[] strSessionTuning = strData.Split('\r', '\n');
                    clsSessionTuningData[] objSessionTuning = new clsSessionTuningData[1];
                    clsDataType.XMLType objXML = new clsDataType.XMLType();

                    int j = 0;
                    for (int i = 0; i < strSessionTuning.GetLength(0); i++)
                    {
                        objXML = clsCommonFunc.GetXML(strSessionTuning[i]);

                        if (objXML != null)
                        {
                            switch (objXML.Name)
                            {
                                case "Revision2":
                                    objSessionTuning[j].bRevision2 = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "Revision3":
                                    objSessionTuning[j].bRevision3 = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "Revision4":
                                    objSessionTuning[j].bRevision4 = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "Revision5":
                                    objSessionTuning[j].bRevision5 = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "Revision6":
                                    objSessionTuning[j].bRevision6 = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "TuningIsNegative":
                                    objSessionTuning[j].bTuningIsNegative = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "Session_ID":
                                    objSessionTuning[j].nSession_ID = int.Parse(objXML.Value);
                                    break;
                                case "SessionTuning_ID":
                                    objSessionTuning[j] = new clsSessionTuningData();
                                    objSessionTuning[j].nSessionTuning_ID = int.Parse(objXML.Value);
                                    break;
                                case "TuningAddInfo":
                                    objSessionTuning[j].nTuningAddInfo = int.Parse(objXML.Value);
                                    break;
                                case "Amp":
                                    objSessionTuning[j].strAmp = objXML.Value;
                                    break;
                                case "Amp2":
                                    objSessionTuning[j].strAmp2 = objXML.Value;
                                    break;
                                case "Amp3":
                                    objSessionTuning[j].strAmp3 = objXML.Value;
                                    break;
                                case "Amp4":
                                    objSessionTuning[j].strAmp4 = objXML.Value;
                                    break;
                                case "Amp5":
                                    objSessionTuning[j].strAmp5 = objXML.Value;
                                    break;
                                case "Amp6":
                                    objSessionTuning[j].strAmp6 = objXML.Value;
                                    break;
                                case "TunFreq":
                                    objSessionTuning[j].strTunFreq = objXML.Value;
                                    break;
                                case "TunFreq2":
                                    objSessionTuning[j].strTunFreq2 = objXML.Value;
                                    break;
                                case "TunFreq3":
                                    objSessionTuning[j].strTunFreq3 = objXML.Value;
                                    break;
                                case "TunFreq4":
                                    objSessionTuning[j].strTunFreq4 = objXML.Value;
                                    break;
                                case "TunFreq5":
                                    objSessionTuning[j].strTunFreq5 = objXML.Value;
                                    break;
                                case "TunFreq6":
                                    objSessionTuning[j].strTunFreq6 = objXML.Value;
                                    break;
                                case "Tuning":
                                    objSessionTuning[j].strTuning = objXML.Value;
                                    break;

                                case "TuningDescr":
                                    objSessionTuning[j].strTuningDescr = objXML.Value;
                                    break;
                                case "AlreadyBalanced":
                                    objSessionTuning[j].bAlreadyBalanced = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "ImagePath":
                                    objSessionTuning[j].strImagePath = objXML.Value;
                                    break;
                                case "Amp7":
                                    objSessionTuning[j].strAmp7 = objXML.Value; // Krunal on 2-2-2012
                                    break;
                                case "TunFreq7":
                                    objSessionTuning[j].strTunFreq7 = objXML.Value;
                                    break;
                                case "Revision7":
                                    objSessionTuning[j].bRevision7 = clsCommonFunc.IsYes(objXML.Value);
                                    break;
                                case "Description":
                                    objSessionTuning[j].Description = objXML.Value;
                                    break;
                                case "TunRevDate":
                                    objSessionTuning[j].strRevDate = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "TunRevDate2":
                                    objSessionTuning[j].strRevDate2 = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "TunRevDate3":
                                    objSessionTuning[j].strRevDate3 = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "TunRevDate4":
                                    objSessionTuning[j].strRevDate4 = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "TunRevDate5":
                                    objSessionTuning[j].strRevDate5 = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "TunRevDate6":
                                    objSessionTuning[j].strRevDate6 = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "TunRevDate7":
                                    objSessionTuning[j].strRevDate7 = Convert.ToDateTime(objXML.Value);
                                    break;
                                case "Tuning_ID":
                                    objSessionTuning[j].nTuning_ID = int.Parse(objXML.Value);
                                    j++;//this is last field so increment by one,
                                    Array.Resize(ref objSessionTuning, j + 1);
                                    break;
                            }
                        }
                    }
                    return objSessionTuning;
                }
                return null;
            }
            catch (Exception ex)
            {
                clsErrorTrace.CreateLog("SessionTuning", ex);
                return null;
            }
        }

但是如果我知道最后一个属性Tuning_ID

,这就行了

有一个简单的方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

当然,有更简单的方法可以做到这一点。其中一个称为Serialization,您可以在其中将整个类转换为某种流,即XML和Bytes。您可以使用XmlSerializer类。这是一个简单的例子:

假设您有一个要存储的类和XML文件:

[Serializable] // you should mark the class as serializable
public class MyData
{
    public int Value { get; set; }
    public string Name { get; set; }
    public string[] SubItems { get; set; }
}

此代码将其转换为XML文件:

MyData data = new MyData();
data.Name = "TestName";
data.Value = 100;
data.SubItems = new string[] {"Item1", "Item2", "Item3"};
XmlSerializer ser = new XmlSerializer(typeof(MyData));
using (FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
    ser.Serialize(file, data);
}

以下是生成的文件:

<?xml version="1.0"?>
<MyData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Value>100</Value>
  <Name>TestName</Name>
  <SubItems>
    <string>Item1</string>
    <string>Item2</string>
    <string>Item3</string>
  </SubItems>
</MyData>

要阅读该文件,请使用Deserialize方法:

using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
    ser.Deserialize(file, data);
}

另一种选择是使用.NET框架中的一个专用类来读取XML文件:

XDocument doc = XDocument.Load(fileName);
List<clsSessionTuningData> objSessionTuning = new List<clsSessionTuningData>()
foreach (var session in doc.Descendants("SessionTuningData"))
{
    XElement elem;
    clsSessionTuningData data = new clsSessionTuningData();
    elem = session.Element("Revision2");
    if (elem != null)
        data.bRevision2 = elem.Value;

    // and so on...
}

答案 1 :(得分:0)

你可以:

1)将您的XML加载到XMLDocument,然后通过其属性(主要是ChildNodes)导航文档;

2)将XML加载到XMLDocument中,然后使用XPath查询文档,通过CreateNavigator创建导航器。

3)使用XmlReader解析文档。

4)创建一组与您的Xml架构密切相关的类,并使用XmlDeserializer将文件映射到一组对象(这很好,但设置起来很棘手,因为XmlDeserializer可以是有点顽固配置)。

如果我需要所有数据,我会选择选项(4),可能会重新设计我的XML /模型类以使转换更容易。

如果我需要一些值,我可能会选择(2),因为它只需要很少的代码。 请参阅(2)here的一些示例。