分析inputstream xml格式java

时间:2018-05-05 06:34:31

标签: java xml inputstream

我有一个InputStream包含xml格式,如下所示: -

InputStream is = asStream("<TransactionList>\n" +
            "    <Transaction type=\"C\" amount=\"1000\"narration=\"salary\" />\n" +
            "    <Transaction type=\"X\" amount=\"400\" narration=\"rent\"/>\n" +
            "    <Transaction type=\"D\" amount=\"750\" narration=\"other\"/>\n" +
            "</TransactionList>");
 xmlTransactionProcessor.importTransactions(is);

我试图分析这个并将值存储到Transaction对象(用户定义的)的数组列表中,但我仍然无法这样做。

我尝试了很多解决方案,但我仍然没有任何好处。

我读过有关读取xml文件的内容,但仍然无法处理像这样的InputStream。

有人可以帮忙吗?这是我的最后一次尝试,但它仍然在某处失败。

    // TODO Auto-generated method stub
    BufferedReader inputReader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String inline = "";
    try {
        while ((inline = inputReader.readLine()) != null) {
          sb.append(inline);
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    SAXBuilder builder = new SAXBuilder();

    try {
        org.jdom2.Document document = (org.jdom2.Document) builder.build(new ByteArrayInputStream(sb.toString().getBytes()));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

2 个答案:

答案 0 :(得分:2)

您不必使用SAX解析器自行解析XML。有几个库允许XML Binding:将XML文档序列化和反序列化为自定义POJO类(或这些类的集合)。

JDK中甚至还有XML绑定标准。它被称为JAXB。您可以使用注释将XML元素名称映射到自定义POJO的属性。

以下是我个人青睐图书馆的示例:Jackson。它主要用于处理JSON格式的文本,但有an extension来支持XML(和JAXB)。

import random

import pygame as pg
from pygame.math import Vector2


pg.init()
BLUE = pg.Color('dodgerblue1')
FONT = pg.font.Font(None, 42)


class Answer(pg.sprite.Sprite):

    def __init__(self, pos, number):
        super().__init__()
        # Store the actual number, so that we can compare it
        # when the user clicks on this object.
        self.number = number
        # Render the new text image/surface.
        self.image = FONT.render(str(number), True, BLUE)
        # A rect with the size of the surface, used for collision
        # detection and rendering.
        self.rect = self.image.get_rect(topleft=pos)
        self.vel = Vector2(0, random.uniform(1, 4))
        self.pos = Vector2(pos)

    def update(self):
        self.pos += self.vel
        self.rect.center = self.pos

        if self.rect.top > 480:  # Screen bottom.
            self.kill()  # Remove the sprite from all groups.


def main():
    screen = pg.display.set_mode((640, 480))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            elif event.type == pg.MOUSEBUTTONDOWN:
                if event.button == 3:  # Right mouse button.
                    # Add 20 numbers (Answer objects).
                    for _ in range(20):
                        number = random.randrange(100)
                        all_sprites.add(Answer((random.randrange(620), -20), number))
                elif event.button == 1:  # Left mouse button.
                    # See if the user clicked on a number.
                    for answer in all_sprites:
                        # event.pos is the mouse position.
                        if answer.rect.collidepoint(event.pos):
                            print(answer.number)


        all_sprites.update()

        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

答案 1 :(得分:0)

正如Sharon Ben Asher所解释的,您可以使用JAXBJackson with XML data formatter使用带注释的数据映射。这会更容易。

如果您想使用SAXParser修复现有代码,请查看其实际情况。

您必须按照以下代码迭代文档对象。

public static void main(String[] args) {
    InputStream is = new ByteArrayInputStream(("<TransactionList>\n" +
            "    <Transaction type=\"C\" amount=\"1000\" narration=\"salary\" />\n" +
            "    <Transaction type=\"X\" amount=\"400\" narration=\"rent\"/>\n" +
            "    <Transaction type=\"D\" amount=\"750\" narration=\"other\"/>\n" +
            "</TransactionList>").getBytes(StandardCharsets.UTF_8));
    ArrayList transactions = importTransactions(is);
}

importTransaction方法中,使用getRootElement获取根级别交易元素。然后使用getChildren和for-each循环遍历每个 Transaction 子元素。

public static ArrayList<Transaction> importTransactions(InputStream is){
        ArrayList<Transaction> transactions = new ArrayList<>();
        BufferedReader inputReader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String inline = "";
        try {
            while ((inline = inputReader.readLine()) != null) {
                sb.append(inline);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        SAXBuilder builder = new SAXBuilder();

        try {
            org.jdom2.Document document = builder.build(new ByteArrayInputStream(sb.toString().getBytes()));
            Element transactionsElement = document.getRootElement();

            List<Element> transactionList = transactionsElement.getChildren();

            for (Element transaction:transactionList) {
                Transaction t = new Transaction();
                t.setType(transaction.getAttribute("type").getValue());
                t.setAmount(transaction.getAttribute("amount").getValue());
                transactions.add(t);

            }

        } catch (Exception e) {
            // Log the error....
            e.printStackTrace();
        }
        return transactions;
    }