【问题标题】:Setting up class for XML deserialization using Simple (XNA to Java porting)使用 Simple(XNA 到 Java 移植)为 XML 反序列化设置类
【发布时间】:2012-11-17 05:02:21
【问题描述】:

我正在尝试将我在 XNA 中使用的类移植到 Android。该类处理读取 XML 文件。

我正在使用 Simple 进行序列化/反序列化,但是我不确定如何设置类以及是否需要 getter/setter。

这是 XNA 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace spritesheetanimation
{
    // Animation frame class
    public class Frame
    {
        // Frame Number
        [XmlAttribute("Num")]
        public int Num;

        // Sub Image X positon in the Sprite Sheet
        [XmlAttribute("X")]
        public int X;

        // Sub Image Y positon in the Sprite Sheet
        [XmlAttribute("Y")]
        public int Y;

        // Sub Image Width
        [XmlAttribute("Width")]
        public int Width;

        // Sub Image Height
        [XmlAttribute("Height")]
        public int Height;

        // The X offset of sub image
        [XmlAttribute("OffSetX")]
        public int OffsetX;

        // The Y offset fo sub image
        [XmlAttribute("OffsetY")]
        public int OffsetY;

        // The duration between two frames
        [XmlAttribute("Duration")]
        public float Duration;
    }

    // Animaiton class to hold the name and frames
    public class Animation
    {
        // Animation Name
        [XmlAttribute("Name")]
        public string Name;

        // Animation Frame Rate
        [XmlAttribute("FrameRate")]
        public int FrameRate;

        public bool Loop;

        public bool Pingpong;

        // The Frames array in an animation
        [XmlArray("Frames"), XmlArrayItem("Frame", typeof(Frame))]
        public Frame[] Frames;
    }

    // The Sprite Texture stores the Sprite Sheet path.fr
    public class SpriteTexture
    {
        // The Sprite Sheet texture file path
        [XmlAttribute("Path")]
        public string Path;
    }

    // Aniamtion Set contains the Sprite Texture and Animaitons.
    [XmlRoot("Animations")]
    public class AnimationSet
    {
        // The sprite texture object
        [XmlElement("Texture", typeof(SpriteTexture))]
        public SpriteTexture SpriteTexture;

        // The animation array in the Animation Set
        [XmlElement("Animation", typeof(Animation))]
        public Animation[] Animations;
    }

    // Sprite Animation Manager class
    public static class SpriteAnimationManager
    {
        public static int AnimationCount;

        // Read the Sprite Sheet Description information from the description xml file
        public static AnimationSet Read(string Filename)
        {
            AnimationSet animationSet = new AnimationSet();

            // Create a XML reader for the sprite sheet animaiton description file
            using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(Filename))
            {
                // Create a XMLSerializer for the AnimationSet
                XmlSerializer serializer = new XmlSerializer(typeof(AnimationSet));

                // Deserialize the Animation Set from the XmlReader to the animation set object
                animationSet = (AnimationSet)serializer.Deserialize(reader);
            }

            // Count the animations to Animation Count
            AnimationCount = animationSet.Animations.Length;

            return animationSet;
        }
    }
}

与我目前的代码进行比较:

package com.example.sprites;
import java.io.InputStream;

import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementArray;
import org.simpleframework.xml.Root;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import org.xmlpull.v1.XmlSerializer;


public class SpriteAnimationManag implements
java.io.Serializable {
   // Animation frame class



   @Element(name = "Frame")
   public class Frame(int num, int x, int y, int width, int height,int offsetx,int offsety, int duration )
   {
      // Frame Number
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlAttribute("Num")]
      @Element(name = "Num")
      public int Num;

      // Sub Image X positon in the Sprite Sheet
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlAttribute("X")]
      @Element(name = "X")
      public int X;

      // Sub Image Y positon in the Sprite Sheet
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlAttribute("Y")]
      @Element(name = "Y")
      public int Y;

      // Sub Image Width
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlAttribute("Width")]
      @Element(name = "Width")
      public int Width;

      // Sub Image Height
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlAttribute("Height")]
      @Element(name = "Height")
      public int Height;

      // The X offset of sub image
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlAttribute("OffSetX")]
      @Element(name = "OffSetX")
      public int OffsetX;

      // The Y offset fo sub image
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlAttribute("OffsetY")]
      @Element(name = "OffSetY")
      public int OffsetY;

      // The duration between two frames
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlAttribute("Duration")]
      @Element(name = "Duration")
      public float Duration;
   }

   // Animaiton class to hold the name and frames
   public class Animation implements
   java.io.Serializable 
   {
      // Animation Name
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlAttribute("Name")]
      @Element(name = "Name")
      public String Name;

      // Animation Frame Rate
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlAttribute("FrameRate")]
      @Element(name = "FrameRate")
      public int FrameRate;


      public boolean Loop;

      public boolean Pingpong;

      // The Frames array in an animation
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlArray("Frames"), XmlArrayItem("Frame", typeof(Frame))]
      @ElementArray(name = "Frames") 
      public Frame[] Frames;
   }

   // The Sprite Texture stores the Sprite Sheet path.fr
   public class SpriteTexture implements
   java.io.Serializable 
   {
      // The Sprite Sheet texture file path
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlAttribute("Path")]
      @Element(name = "path")
      public String Path;
   }

   // Aniamtion Set contains the Sprite Texture and Animaitons.
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
   //[XmlRoot("Animations")]
   @Root
   public static class XNAAnimationSet implements
    java.io.Serializable
   {
      // The sprite texture object
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlElement("Texture", typeof(SpriteTexture))]
      @Element(name = "Texture")
      public SpriteTexture SpriteTexture;

      // The animation array in the Animation Set
   //C# TO JAVA CONVERTER TODO TASK: Java annotations will not correspond to .NET attributes:
      //[XmlElement("Animation", typeof(Animation))]
      @ElementArray(name = "Animation")
      public Animation[] Animations;
   }

   // Sprite Animation Manager class
   public final static class SpriteAnimationManager implements
    java.io.Serializable
   {
      private static final String XNAAnimationSet = null;//was static private static
      public static int AnimationCount;

      // Read the Sprite Sheet Description information from the description xml file
      public static XNAAnimationSet Read(InputStream inputStream) throws Exception
      {

          XNAAnimationSet animationSet = new XNAAnimationSet();


         // Create a XML reader for the sprite sheet animaiton description file
   //C# TO JAVA CONVERTER NOTE: The following 'using' block is replaced by its Java equivalent:
//       using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(Filename))
         //System.Xml.XmlReader reader = System.Xml.XmlReader.Create(Filename);
         //XMLReader reader = XMLReaderFactory.createXMLReader(Filename);//i added this 


            // Create a XMLSerializer for the AnimationSet
            //XmlSerializer serializer = new XmlSerializer(AnimationSet);
                //i added below using simple//
             Serializer serializer = new Persister();
             //serializer.read(AnimationSet, Filename);
             try {
               animationSet = serializer.read(XNAAnimationSet.class, inputStream );
            } 
             catch (Exception e)
             {
               // TODO Auto-generated catch block
               e.printStackTrace();
            }
            ///////////////
            // Desesrialize the Animation Set from the XmlReader to the animation set object
         // animationSet = (AnimationSet)serializer1.Deserialize(reader);
            //serializer.write(AnimationSet, animationSet);
         //}
         //finally
         //{
            //reader.dispose(); //doesn'twork
      // }

         // Count the animations to Animation Count
         AnimationCount = animationSet.Animations.length;

         return animationSet;
      }
   }
}

是的,我确实将代码放入了转换器,但是我已经对其进行了很多更改(但是尚未删除自动生成的 cmets)。

我只是想看看如何设置其中一个类,其余的可能我可以自己完成,但是我是一名新手程序员,过去 2 天我一直在搜索和试验,但是我做了几件事不知道。

【问题讨论】:

  • 在问题中发布相关代码通常比仅仅链接到外部网站更好。
  • 我试过了,但它不允许我发布,因为以代码框格式获取所有代码时出现问题。它会随机决定排除部分代码,然后不允许我发布
  • user1831330:听起来你以前从未在 Markdown 中写过。写一切的时候看看markdown代码语法。
  • 我有一个别名可以帮助解决这个问题:alias markdown-prepare="sed 's/(.*)/ \1/'"

标签: java xml serialization xna


【解决方案1】:

simple-xml 的工作方式是用标签注释一个类,然后调用一个函数来实际序列化数据。看看我的blog post on the topic这个例子:

// Create the Dummy Level with Apples and Oranges
Log.i(TAG, "Create level");
Level level = new Level();
Orange orange;
level.gameObjects.add(new Apple(1, 10));
orange = new Orange(2);
orange.containedJuice = 20;
level.gameObjects.add(orange);
orange = new Orange(3);
orange.containedJuice = 100;
level.gameObjects.add(orange);
level.gameObjects.add(new Apple(4, 0));

// Now write the level out to a file
Log.i(TAG, "Write Level to file.");
Serializer serial = new Persister();
File sdcardFile = new File("/sdcard/levelout.xml");

try {
   serial.write(level, sdcardFile);
} catch (Exception e) {
   // There is the possibility of error for a number of reasons. Handle this appropriately in your code
   e.printStackTrace();
}
Log.i(TAG, "XML Written to File: " + sdcardFile.getAbsolutePath());

现在真的只有三个步骤:

  1. 创建“关卡”对象。
  2. 创建一个“Serializer”对象并指定要写入 xml 的位置。
  3. 实际上使用'serial.write'函数编写XML

要执行读取,您仍然需要一个带注释的“Level”类,但您在“Serializer”类上调用“read”函数,它会为您构造一个类。我希望这能回答你的问题。

【讨论】:

  • 感谢您的快速回复!其实我之前确实看过你的帖子。但是我不知道如何注释类,这是我的麻烦。例如,我尝试使用 public class Frame (int a, int b) {} 但它希望我将其声明为无效,这会导致进一步的问题。您可以查看 XNA 代码以了解我正在尝试做什么(它实际上非常干净而且不是非常特定于 XNA)
  • 如果您不知道如何注释类,那么这就是简单 XML 教程的用途:simple.sourceforge.net/download/stream/doc/tutorial/…
  • 啊哈我正在阅读它,但显然没有得到它。 XNA 中的最后一个问题是元素“Typeof”的标记,这相当于“属性”吗?
  • 这是元素的类类型吗?如果是泛型类型?因为 SimpleXML 也有类似的东西,但我不记得它叫什么。
  • 这就是为什么我添加了我的 C# 代码,它非常干净、易于阅读并且可以工作,因此您可以看到我正在尝试做什么。所以是的,我想这就是元素的类类型。这甚至有必要吗?当我从我的 C# 代码中取出它时,它无论如何都可以工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
相关资源
最近更新 更多