【问题标题】:Getting the information from xml from inpustream java从 inputstream java 中获取 xml 的信息
【发布时间】:2013-10-01 18:26:45
【问题描述】:

我有这个程序从输入流中读取 xml,这是输入流的结果 xml

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
    <GetRouteSummaryForStopResponse xmlns="http://octranspo.com">
        <GetRouteSummaryForStopResult>
            <StopNo xmlns="http://tempuri.org/">string</StopNo>
            <StopDescription 
             xmlns="http://tempuri.org/">string</StopDescription>
            <Error xmlns="http://tempuri.org/">string</Error>
            <Routes xmlns="http://tempuri.org/">
                <Route>
                    <RouteNo>int</RouteNo>
                    <DirectionID>int</DirectionID>
                    <Direction>string</Direction>
                    <RouteHeading>string</RouteHeading>
                </Route>
                <Route>
                    <RouteNo>int</RouteNo>
                    <DirectionID>int</DirectionID>
                    <Direction>THIS IS A STRING</Direction>
                    <RouteHeading>string</RouteHeading>
                </Route>
            </Routes>
        </GetRouteSummaryForStopResult>
    </GetRouteSummaryForStopResponse>
</soap:Body>
</soap:Envelope>

我不知道从哪里开始获取 xml 中的方向信息。

public String HTTPrequest(String stopNo){
    String parameterURL = "appID="+this.appId+"&apiKey="+this.AppKey+"&routeNo=1&stopNo="+stopNo+"";    
    URL url;
    HttpURLConnection connection = null;
    try {
        url = new URL(this.requestGetRouteSummaryForStop);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false); 
        connection.setRequestMethod("POST"); 
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(parameterURL.getBytes().length));
        connection.setUseCaches (false);

        //send request
         DataOutputStream wr = new DataOutputStream (
                  connection.getOutputStream ());
                  wr.writeBytes (parameterURL);
                  wr.flush ();
                  wr.close ();

        //Get Response  

          InputStream is = connection.getInputStream();
          BufferedReader rd = new BufferedReader(new InputStreamReader(is));
          String line;
          StringBuffer response = new StringBuffer(); 
          while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
          }
          rd.close();
          System.out.print(response.toString());
      return response.toString();
    } catch (Exception e) {
        System.out.print("ERROR: ");
        e.printStackTrace();
        return null;
    }finally{
        if(connection != null){
            connection.disconnect();
        }
    }
}


public void parseXmlData(String response){
    InputSource xmlSource = new InputSource(new StringReader(response));
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(xmlSource);

        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();

        String routeHeading = xPath.evaluate("/GetRouteSummaryForStopResponse/GetRouteSummaryForStopResult/Routes/Route/Direction",document);
        System.out.print("RouteHeading: "+ routeHeading);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这是解析xml并连接主机的代码

___________________:EDIT:_______ ______________

    public InputStream HTTPrequest(String stopNo){
    String parameterURL = "appID="+this.appId+"&apiKey="+this.AppKey+"&routeNo=1&stopNo="+stopNo+"";    
    URL url;
    HttpURLConnection connection = null;
    try {
        url = new URL(this.requestGetRouteSummaryForStop);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setInstanceFollowRedirects(false); 
        connection.setRequestMethod("POST"); 
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
        connection.setRequestProperty("charset", "utf-8");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(parameterURL.getBytes().length));
        connection.setUseCaches (false);

        //send request
         DataOutputStream wr = new DataOutputStream (
                  connection.getOutputStream ());
                  wr.writeBytes (parameterURL);
                  wr.flush ();
                  wr.close ();

        //Get Response  

          InputStream is = connection.getInputStream();
         return is;
    } catch (Exception e) {
        System.out.print("ERROR: ");
        e.printStackTrace();
        return null;
    }finally{
        if(connection != null){
            connection.disconnect();
        }
    }
}


public void parseXmlData(InputStream response){
    InputStream is = response;

    try {

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(false);
        Document doc = dbf.newDocumentBuilder().parse(is);

        XPathFactory xf = XPathFactory.newInstance();
        XPath xPath = xf.newXPath();

        // Find direction ANY where within the document...

        XPathExpression xExp = xPath.compile("//DirectionID");
        NodeList nl = (NodeList) xExp.evaluate(doc, XPathConstants.NODESET);
        for (int index = 0; index < nl.getLength(); index++) {
            Node node = nl.item(index);
            System.out.println(node.getTextContent());
        }

        // Find the direction node's any where in the document
        // where it's a child of Route, which has a child
        // node called RouteNo with the text value of 'int'...
        xExp = xPath.compile("//Route[RouteNo = 'int']/Direction");
        nl = (NodeList) xExp.evaluate(doc, XPathConstants.NODESET);
        for (int index = 0; index < nl.getLength(); index++) {
            Node node = nl.item(index);
            System.out.println(node.getTextContent());
        }

    } catch (Exception exp) {
        exp.printStackTrace();
    }
}

它给我一个错误

[Fatal Error] :1:1: Premature end of file.
org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Premature end of file.
    at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(Unknown Source)
    at OcTranspoConnect.parseXmlData(OcTranspoConnect.java:82)
    at OcTranspoConnect.main(OcTranspoConnect.java:29)

【问题讨论】:

  • 使用 XML 解析器?还是您已经在使用其中一个并且遇到了问题?
  • @WilliamGaul 是的,我愿意。我将编辑我的帖子..并发布我的代码

标签: java xml inputstream


【解决方案1】:

你有两个选择开始......

你可以

将 XML 加载到文档对象模型中。这允许您完全访问 XML 以对其进行查询(并可能对其进行修改)。

如果您需要进行多次处理或想要对数据进行多次查询,因为 DOM 已加载到内存中并且始终可用。

如果 XML 文件很大就不太好,因为 DOM 需要相当大的内存

DOM 方法使您能够使用XPath 支持。 XPath 是 XML 的查询 API(甚至可以用于结构良好的 HTML)

查看Document Object Model了解更多详情。

你可以

使用 SAX 解析器在加载 XML 文档时对其进行处理。这提供了回调方法/事件,当解析过程中的某些东西引发它们时,它们会被调用。

当文档很大或者您只需要对文档进行一次处理(例如构建您自己的文档对象表示)时,这很好。

它不太适合多遍处理或交互式查询。

查看Simple API for XML了解更多详情

更新了 XPath 示例

虽然我确信处理命名空间很容易,但对我来说,它只是碍事。

以下是两个 XPath 查询的简单示例,从您的问题中查找文档中的所有 Direction 节点

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XPathTest {

    public static void main(String[] args) {

        InputStream is = null;

        try {
            is = new FileInputStream("Soap.xml");

            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(false);
            Document doc = dbf.newDocumentBuilder().parse(is);

            XPathFactory xf = XPathFactory.newInstance();
            XPath xPath = xf.newXPath();

            // Find direction ANY where within the document...

            XPathExpression xExp = xPath.compile("//Direction");
            NodeList nl = (NodeList) xExp.evaluate(doc, XPathConstants.NODESET);
            for (int index = 0; index < nl.getLength(); index++) {
                Node node = nl.item(index);
                System.out.println(node.getTextContent());
            }

            // Find the direction node's any where in the document
            // where it's a child of Route, which has a child
            // node called RouteNo with the text value of 'int'...
            xExp = xPath.compile("//Route[RouteNo = 'int']/Direction");
            nl = (NodeList) xExp.evaluate(doc, XPathConstants.NODESET);
            for (int index = 0; index < nl.getLength(); index++) {
                Node node = nl.item(index);
                System.out.println(node.getTextContent());
            }

        } catch (ParserConfigurationException | SAXException | IOException | XPathExpressionException exp) {
            exp.printStackTrace();
        }
    }
}

这输出...

string
THIS IS A STRING
string
THIS IS A STRING

【讨论】:

  • 是的,我使用 XPath,但我无法在“方向”中获取数据
  • 如何使用 XPath 实现命名空间
  • 嗨 madprogrammer 我试图将您的代码添加到我的代码中,抱歉使用它。但它给了我一个错误并且不会让我读取 xml 我认为问题是从 HTTPrequest() 到 INPUTSTREAM 的返回对吗??
  • 我已经修好了。我添加了一个 InputSource 并将响应添加到 documentbuilder.. THX 的帮助.. 你的代码真的很有帮助
猜你喜欢
  • 1970-01-01
  • 2014-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
  • 2012-03-13
  • 1970-01-01
相关资源
最近更新 更多