Как встроить XML-файл в пакет Java и получить к нему доступ? - PullRequest
3 голосов
/ 16 февраля 2010

У меня есть XML-файл с данными, который используется как в моей C #, так и в Java-версии библиотеки. В идеале я хочу встроить этот XML-файл в пакет этой библиотеки.

Мне нужно получить к ней доступ только из моей библиотеки, поэтому мне было интересно: возможно ли это?

Ответы [ 2 ]

9 голосов
/ 16 февраля 2010

В Java вы можете включить сам файл XML в файл JAR. Затем вы можете использовать что-то вроде этого:

InputStream istream = getClass().getResourceAsStream("/resource/path/to/some.xml");

И проанализируйте ваш InputStream как обычно.

Вышеупомянутый getResourceAsStream() ищет текущий путь к классу, который будет включать содержимое любых файлов JAR.

0 голосов
/ 04 января 2013
book.xml
<book>
<person>
  <first>Kiran</first>
  <last>Pai</last>
  <age>22</age>
</person>
<person>
  <first>Bill</first>
  <last>Gates</last>
  <age>46</age>
</person>
<person>
  <first>Steve</first>
  <last>Jobs</last>
  <age>40</age>
</person>
<person>
  <first>kunal</first>
  <last>kumar</last>
  <age>25</age>
</person>
</book>

create a xml file book.xml
made a jar file book.xml.jar and 
palce it in war/web-inf/lib folder of your project..
 then it will work..
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;




import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

@SuppressWarnings("serial")
public class XMLParser extends HttpServlet {
    InputStream istream =getClass().getResourceAsStream("/book.xml");
    public void doGet(HttpServletRequest req, HttpServletResponse resp)throws IOException
    {

        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = null;
        try {
            docBuilder = docBuilderFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
      Document doc = null;
    try {
        doc = docBuilder.parse (istream);
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

        // normalize text representation
        doc.getDocumentElement ().normalize ();
        System.out.println ("Root element of the doc is " + 
             doc.getDocumentElement().getNodeName());


        NodeList listOfPersons = doc.getElementsByTagName("person");
        int totalPersons = listOfPersons.getLength();
        System.out.println("Total no of people : " + totalPersons);

        for(int s=0; s<listOfPersons.getLength() ; s++){


            Node firstPersonNode = listOfPersons.item(s);
            if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){


                Element firstPersonElement = (Element)firstPersonNode;

                //-------
                NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                Element firstNameElement = (Element)firstNameList.item(0);

                NodeList textFNList = firstNameElement.getChildNodes();
                System.out.println("First Name : " + 
                       ((Node)textFNList.item(0)).getNodeValue().trim());

                //-------
                NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                Element lastNameElement = (Element)lastNameList.item(0);

                NodeList textLNList = lastNameElement.getChildNodes();
                System.out.println("Last Name : " + 
                       ((Node)textLNList.item(0)).getNodeValue().trim());

                //----
                NodeList ageList = firstPersonElement.getElementsByTagName("age");
                Element ageElement = (Element)ageList.item(0);

                NodeList textAgeList = ageElement.getChildNodes();
                System.out.println("Age : " + 
                       ((Node)textAgeList.item(0)).getNodeValue().trim());

                //------


            }//end of if clause


        }//end of for loop with s var

    //System.exit (0);

}//end of main


    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...