来自XML的Java文件名

时间:2015-11-08 22:34:09

标签: java xml xml-parsing

我正在尝试使用xml发布日期的名称保存文件。 我的代码不起作用(除了其他方面,但是没有获取日期并以日期作为名称保存文件的部分)

    public static void main(String[] args) throws Exception  {
    URL oracle = new URL("http://www.bnr.ro/nbrfxrates.xml");
    URLConnection yc = oracle.openConnection();
    StringWriter sw = new StringWriter();
    StringWriter filename = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    PrintWriter out = new PrintWriter(filename+".xml");
    BufferedReader in = new BufferedReader(new InputStreamReader(
                            yc.getInputStream()));
    String inputLine;


    while ((inputLine = in.readLine()) != null) { 

        pw.println(inputLine);
        out.println(inputLine);
    }
    in.close();
    pw.close();
    sw.close();
    out.close();

    String data = sw.toString();
    String test = filename.toString();

        Map<String,Double> currencies = new HashMap<String,Double>();
            Pattern pattern = Pattern.compile("<Rate currency=\"([^\"]{3})\">(.+?)</Rate>");
            Matcher matcher = pattern.matcher(data);
            Pattern date = Pattern.compile("<PublishingDate>(.+?)</PublishingDate>");
            Matcher datem = date.matcher(test);
            int pos = 0;
            while(matcher.find(pos)) {
              System.out.println("Found: " + matcher.group(1) + ": " + Double.valueOf(matcher.group(2)));
              currencies.put(matcher.group(1), Double.valueOf(matcher.group(2)));
              pos = matcher.end();
            }
            Scanner keyboard = new Scanner(System.in);

            boolean ok = true;
            while(ok) {
              System.out.println("What currency rate do you need? (QUIT to quit)");
              String cur = keyboard.nextLine();
              System.out.println("Rate for " + cur + " is " + currencies.get(cur));
              if("QUIT".equalsIgnoreCase(cur)) {
                ok = false;
              }else{
                  System.out.println("That`s not an option");
              }
            }    
            keyboard.close();
  }
}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

更好地使用XML解析器而不是正则表达式

首先:在获得此名称之前,您可以使用文件名保存文件。

试试这个:

// First get Your URL INTO STRING (why not into File ...)
URL url=new URL ("http://www.bnr.ro/nbrfxrates.xml");
URLConnection urlConnection = url.openConnection();
HttpURLConnection connection = null;
if(urlConnection instanceof HttpURLConnection)
   connection = (HttpURLConnection) urlConnection;
  // ELSE => STOP
BufferedReader in = new BufferedReader(new    InputStreamReader(connection.getInputStream()));

String urlString = "";
String current;
while((current = in.readLine()) != null)
   urlString += current+"\n";

// Now, You have your XML in urlString

// Do that because of xsi
xml="<root xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"+
xml+
"</root>";

DocumentBuilderFactory builderFactory =DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
DocumentBuilder builder = builderFactory.newDocumentBuilder();
//PARSE
Document document = builder.parse(new InputSource(new StringReader(urlString)));

XPath xPath = XPathFactory.newInstance().newXPath();
//read a string value
String expression = "/root/DataSet/Header/PublishingDate";

NodeList nodes  = (NodeList)  xPath.compile(expression).evaluate(document, XPathConstants.NODESET);

String the_date="";

for(int i=0; i<nodes.getLength(); i++)
    {
    Node the_node = nodes.item(i);

    if(the_node instanceof Element)
    {
     Element the_element=(Element) the_node;
     the_date=the_element.getTextContent();
     break;
    }
}

// WELL: YOU HAVE the_date, you can use it as a filename

File fileout=new File(the_date+".xml");
Writer out = new OutputStreamWriter(new FileOutputStream(fileout));
out.write(xml);
out.close();