Java 来自 HTTP 的 XML 解析文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3058434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:04:52  来源:igfitidea点击:

XML parse file from HTTP

javaxml

提问by Travis

I have an XML file located at a location such as

我有一个位于诸如的位置的 XML 文件

http://example.com/test.xml

I'm trying to parse the XML file to use it in my program with xPath like this but it is not working.

我正在尝试解析 XML 文件以在我的程序中使用它,像这样使用 xPath 但它不起作用。

Document doc = builder.parse(new File(url));

How can I get the XML file?

如何获取 XML 文件?

回答by laz

Get rid of the new File():

摆脱new File()

Document doc = builder.parse(url);

回答by Nils

It's much easier with a XMLPullParser ... you don't have to deal with this event stuff and can quickly pick up some keywords ... I'm using it too ... only a couple of code lines :)

使用 XMLPullParser 会容易得多......你不必处理这些事件,并且可以快速选择一些关键字......我也在使用它......只有几行代码:)

http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html

http://developer.android.com/reference/org/xmlpull/v1/XmlPullParser.html

Regarding HTTP and files have a look here Download a file with DefaultHTTPClient and preemptive authentication

关于 HTTP 和文件,请查看此处 下载带有 DefaultHTTPClient 和抢占式身份验证的文件

回答by santiagobasulto

A little more detail, based on laz answer:

更详细一点,基于 laz 的回答:

String urlString = "http://example.com/test.xml";
URL url = new URL(urlString);
Document doc = builder.parse(url);

回答by Matteo

File fileXml = new File(url);

DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document document = parser.parse(fileXml);

it should go

它应该去

回答by Favonius

Try using URLConnection.getInputStream()for getting the handle of XML file.

尝试URLConnection.getInputStream()用于获取 XML 文件的句柄。

See the below code, in that I am trying to open an xml file and printing all the descriptionfields:

请参阅下面的代码,因为我正在尝试打开一个 xml 文件并打印所有description字段:

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

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

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class HTTPXMLTest
{
    public static void main(String[] args) 
    {
        try {
            new HTTPXMLTest().start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void start() throws Exception
    {
        URL url = new URL("http://localhost:8080/AutoLogin/resource/web.xml");
        URLConnection connection = url.openConnection();

        Document doc = parseXML(connection.getInputStream());
        NodeList descNodes = doc.getElementsByTagName("description");

        for(int i=0; i<descNodes.getLength();i++)
        {
            System.out.println(descNodes.item(i).getTextContent());
        }
    }

    private Document parseXML(InputStream stream)
    throws Exception
    {
        DocumentBuilderFactory objDocumentBuilderFactory = null;
        DocumentBuilder objDocumentBuilder = null;
        Document doc = null;
        try
        {
            objDocumentBuilderFactory = DocumentBuilderFactory.newInstance();
            objDocumentBuilder = objDocumentBuilderFactory.newDocumentBuilder();

            doc = objDocumentBuilder.parse(stream);
        }
        catch(Exception ex)
        {
            throw ex;
        }       

        return doc;
    }
}

回答by Krishna

Here is the simple example for getting data form this string "http://www.gettingagile.com/feed/rss2/"

这是从这个字符串“ http://www.gettingagile.com/feed/rss2/”中获取数据的简单示例

public class MainClassXml {

    public static void main(String args[]) throws URISyntaxException,
            ClientProtocolException, IOException, MalformedURLException {

        String url = "http://www.gettingagile.com/feed/rss2/";
        System.out.println("Url is careated****");
        URL url2 = new URL(url);
        HttpGet httpGet = new HttpGet(url);
        HttpClient httpClient = new DefaultHttpClient();

        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity entity = httpResponse.getEntity();
        System.out.println("Entity is*****" + entity);
        try {
            String xmlParseString = EntityUtils.toString(entity);
            System.out.println("This Stirng to be Pasrse***" + xmlParseString);

            HttpURLConnection connection = (HttpURLConnection) url2
                    .openConnection();
            InputStream inputStream = connection.getInputStream();

            DocumentBuilderFactory builderFactory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder documentBuilder = builderFactory
                    .newDocumentBuilder();
            Document document = documentBuilder.parse(inputStream);
            document.getDocumentElement().normalize();

            System.out.println("Attributes are***" + document.getAttributes());

            NodeList nodeList = document.getElementsByTagName("rss");
            System.out.println("This is firstnode" + nodeList);
            for (int getChild = 0; getChild < nodeList.getLength(); getChild++) {

                Node Listnode = nodeList.item(getChild);
                System.out.println("Into the for loop"
                        + Listnode.getAttributes().getLength());
                Element firstnoderss = (Element) Listnode;
                System.out.println("ListNodes" + Listnode.getAttributes());
                System.out.println("This is node list length"
                        + nodeList.getLength());

                Node Subnode = nodeList.item(getChild);
                System.out.println("This is list node" + Subnode);
                System.out.println("rss attributes***************");
            }

        } catch (Exception exception) {

            System.out.println("Exception is" + exception);

        }
    }