Android编程如何获取XML字符串有序标签

时间:2012-10-28 21:08:37

标签: android tags xmlserializer stringwriter

我写了这个Code.It很棒。但是我的输出字符串有问题。

   public static String CreateIndexForImage() 
   throws IllegalArgumentException, IllegalStateException, IOException
{
   String Image_Name = "Bla BLa";

   static XmlSerializer xmlSerializer = Xml.newSerializer();
   static StringWriter writer = new StringWriter();
   xmlSerializer.setOutput(writer);

   xmlSerializer.startDocument("UTF-8", true);

   xmlSerializer.startTag("", "imagefile");
   xmlSerializer.startTag("", "image");
   xmlSerializer.startTag("", "name");

   xmlSerializer.text(Image_Name);

   xmlSerializer.endTag("", "name");
   xmlSerializer.endTag("", "image");
   xmlSerializer.endTag("", "imagefile"); 

   xmlSerializer.endDocument();

   return writer.toString();
 }

输出如下:

  <?xml version='1.0' encoding='UTF-8' standalone='yes' ?><imagefile><image><name>Bla Bla</name></image></imagefile>

但我希望输出的顺序如下:

 <?xml version='1.0' encoding='UTF-8' standalone='yes' ?>
 <imagefile>
      <image>
         <name>Bla BLa</name>
      </image>
 </imagefile>

在XmlSerializer类或StringWriter类中是否有这样的方法或类似内容? 否则我可以用另一种方式来命令上面的行。

1 个答案:

答案 0 :(得分:2)

你有没有尝试过类似的东西?

serializer.setProperty(
"http://xmlpull.org/v1/doc/properties.html#serializer-indentation", "   ");

serializer.setProperty(
"http://xmlpull.org/v1/doc/properties.html#serializer-line-separator", "\n");

我不知道这是否仍然有效。否则你可以试试这样的东西:

serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);