从XML转换数组

时间:2012-08-17 23:22:57

标签: c# xml xpath xml-serialization

在我的文件中使用XML并想要序列化然后反序列化对象,我有些新手。该对象包含一对字符串,一个int,然后是两个int []数组。使用XmlSerializer进行序列化很好,生成的XML看起来像这样:

http://codepaste.net/x9x5ms

<?xml version="1.0" encoding="utf-16"?>
<Harvey xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Carl</Name>
  <Ch>KNV</Ch>
  <Tn>40</Tn>
  <APoints>
    <int>8</int>
    <int>20</int>
    <int>16</int>
    <int>16</int>
    <int>12</int>
    <int>12</int>
    <int>16</int>
    <int>16</int>
    <int>4</int>
    <int>4</int>
    <int>4</int>
  </APoints>
  <SPoints>
    <int>3</int>
    <int>12</int>
    <int>10</int>
    <int>10</int>
    <int>6</int>
    <int>6</int>
    <int>10</int>
    <int>10</int>
  </SPoints>
</Harvey>

问题是尝试将int []值加载回其数组中。我无法弄清楚如何告诉应用程序我想将所有Apoints加载到int []数组中。我怀疑解决方案非常简单,但我一直无法弄明白。

3 个答案:

答案 0 :(得分:8)

一样简单

[XmlRoot( "Harvey" )]
public class Widget
{

    [XmlElement]
    public string Name { get ; set; }

    [XmlElement]
    public string Ch   { get ; set; }

    [XmlElement]
    public int    Tn   { get ; set; }

    [XmlArray("APoints")]
    [XmlArrayItem("int")]
    public int[] APoints { get ; set ; }

    [XmlArray("SPoints")]
    [XmlArrayItem("int")]
    public int[] SPoints { get ; set ; }

}

class Program
{
    public static T Rehydrate<T>( string xml )
    {
        T instance ;
        XmlSerializer serializer = new XmlSerializer( typeof(T) ) ;

        using ( TextReader tr = new StringReader( xml ) )
        {
            instance = (T) serializer.Deserialize( tr ) ;
        }
        return instance ;
    }


    static void Main( string[] args )
    {
        string xml = @"
<Harvey xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
  <Name>Carl</Name>
  <Ch>KNV</Ch>
  <Tn>40</Tn>
  <APoints>
    <int>8</int>
    <int>20</int>
    <int>16</int>
    <int>16</int>
    <int>12</int>
    <int>12</int>
    <int>16</int>
    <int>16</int>
    <int>4</int>
    <int>4</int>
    <int>4</int>
  </APoints>
  <SPoints>
    <int>3</int>
    <int>12</int>
    <int>10</int>
    <int>10</int>
    <int>6</int>
    <int>6</int>
    <int>10</int>
    <int>10</int>
  </SPoints>
</Harvey>
";
        Widget instance = Rehydrate<Widget>( xml ) ;

        return;
    }

}

答案 1 :(得分:1)

比序列化更简单的东西

XmlReader reader = XmlReader.Create(new StringReader(xml));
XElement root = XElement.Load(reader);

int[] myInts = ((IEnumerable)root.XPathEvaluate("APoints/int"))
                 .OfType<XElement>()
                 .Select(el => int.Parse(el.Value))
                 .ToArray();

答案 2 :(得分:-1)

这是我前一段时间写的课程:

public static class Serializer
{
    // returns false in case of an error
    public static bool save(string fileName, Object obj)
    {
        XmlSerializer serializer = null;
        TextWriter textWriter = null;
        bool res = false;

        try
        {
            serializer = new XmlSerializer(obj.GetType());
            textWriter = new StreamWriter(fileName);
            serializer.Serialize(textWriter,obj);
            res = true;
        }
        catch(Exception ex)
        {
            // handle error
        }
        finally
        {
            if (null != textWriter)
                textWriter.Close();
        }

        return res;
    }

    // returns null in case of an error
    public static Object load(Type type, string fileName)
    {
        XmlSerializer deserializer=null;
        TextReader textReader=null;
        Object res = null;
        try
        {
            deserializer = new XmlSerializer(type);
            textReader = new StreamReader(fileName);
            res=deserializer.Deserialize(textReader);

        }
        catch(Exception ex)
        {
            // handle error
        }
        finally
        {
            if (null != textReader)
                textReader.Close();
        }

        return res;
    }
}

这就是你如何使用它:

public class Data
{
    public int a;
    public int[] arr;
}

private void button1_Click(object sender, EventArgs e)
{
    Data myData = new Data();
    myData.a = 2;
    myData.arr=new int[]{1,2,3,7};
    Serializer.save("file.xml", myData);
}

private void button2_Click(object sender, EventArgs e)
{
    Data myData;
    myData = (Data)Serializer.load(typeof(Data), "file.xml");

}