首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Java中,可以使用哪些方法从文件中返回有效和无效的XML数据?

在Java中,可以使用哪些方法从文件中返回有效和无效的XML数据?
EN

Stack Overflow用户
提问于 2018-08-25 06:19:49
回答 2查看 164关注 0票数 3

我有以下应该是XML的数据:

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<Product>
    <id>1</id>
    <description>A new product</description>
    <price>123.45</price>
</Product>

<Product>
    <id>1</id>
    <description>A new product</description>
    <price>123.45</price>
</Product>

<ProductTTTTT>
    <id>1</id>
    <description>A new product</description>
    <price>123.45</price>
</Product>

<Product>
    <id>1</id>
    <description>A new product</description>
    <price>123.45</price>
</ProductAAAAAA>

所以,基本上我有多个根元素(product)...

重点在于,我正在尝试将这些数据转换为2个XML文档,1个用于有效节点,其他用于无效节点。

有效节点:

代码语言:javascript
复制
<Product>
   ...
</Product>

无效节点:<ProductTTTTT>...</Product><Product>...</ProductAAAAAA>

然后我在想如何使用JAVA (而不是web)来实现这一点。

  • 如果我没记错,用XSD验证它会使整个文件无效,所以不是一个选项。
  • 使用默认的JAXB解析器(解组程序)会导致上面的项目,因为它在内部创建了我的实体的XSD。
  • 使用XPath (据我所知)只会返回整个文件,我没有找到方法来获得像get !VALID这样的东西(它只是到 XQuery (也许?)顺便说一下,如何在JAXB中使用XQuery?
    • XSL(T)在XPath上也会导致同样的事情,因为它使用XPath来选择内容。

所以..。我可以使用哪种方法来实现此目标?(如果可能,请提供链接或代码)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-25 09:27:47

如果文件包含名称以"Product“开头的开始和结束标记的行,您可以:

只要一行以XML或</Product

  • attempt开头,使用XML将提取的文本解析为,
  • 就会使用文件扫描程序将该文档拆分为多个部分。
    • 如果成功,则将该对象添加到格式良好的XML文档列表中(
      • ),然后执行任何附加的模式验证或有效性验证。

代码语言:javascript
复制
- If it throws a parse error, catch it, and add that snippet of text to the list of "bad" items that need to be cleaned up or otherwise handled

下面是一个帮助您入门的示例:

代码语言:javascript
复制
package com.stackoverflow.questions.52012383;

import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FileSplitter {

    public static void parseFile(File file, String elementName) 
      throws ParserConfigurationException, IOException {

        List<Document> good = new ArrayList<>();
        List<String> bad = new ArrayList<>();

        String start-tag = "<" + elementName;
        String end-tag = "</" + elementName;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder;
        StringBuffer buffer = new StringBuffer();
        String line;
        boolean append = false;

        try (Scanner scanner = new Scanner(file)) {
            while (scanner.hasNextLine()) {
                line = scanner.nextLine();

                if (line.startsWith(startTag)) {
                    append = true; //start accumulating content
                } else if (line.startsWith(endTag)) {
                    append = false;
                    buffer.append(line); 
                    //instead of the line above, you could hard-code the ending tag to compensate for bad data:
                    // buffer.append(endTag + ">");

                    try { // to parse as XML
                        builder = factory.newDocumentBuilder();
                        Document document = builder.parse(new InputSource(new StringReader(buffer.toString())));
                        good.add(document); // parsed successfully, add it to the good list

                        buffer.setLength(0); //reset the buffer to start a new XML doc

                    } catch (SAXException ex) {
                        bad.add(buffer.toString()); // something is wrong, not well-formed XML
                    }
                }

                if (append) { // accumulate content
                    buffer.append(line);
                }
            }
            System.out.println("Good items: " + good.size() + " Bad items: " + bad.size());
            //do stuff with the good/bad results...
        }
    }

    public static void main(String args[]) 
      throws ParserConfigurationException, IOException {
        File file = new File("/tmp/test.xml");
        parseFile(file, "Product");
    }

}
票数 1
EN

Stack Overflow用户

发布于 2018-08-25 06:44:06

首先,你混淆了有效的和格式良好的。你说你想找到无效的元素,但是你的例子不仅仅是无效的,它们是病态的。这意味着除了向您抛出一条错误消息外,任何XML解析器都不会对它们做任何事情。不能使用JAXB、XPath、XQuery、XSLT或任何东西来处理非XML的内容。

您可以说“很遗憾,我无法访问发送此xml格式的系统”。我不明白为什么你把它叫做XML格式:它不是,我也不明白为什么你(和StackOverflow上的许多其他人)准备把你的时间花在这样的垃圾东西上,而不是告诉发送者把他们的行动起来。如果你被端上一份里面有蠕虫的沙拉,你会试着把它们挑出来,还是会把它送回去换掉?你应该对坏数据采取零容忍的方法;这是发送者学会提高质量的唯一方法。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52012383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档