如何使用Java代码将以下内容转换为MON-FRI

时间:2011-03-31 05:21:18

标签: java

<Days>
    <day>Mon</day>
     <day>Tue</day>
     <day>Wed</day>
     <day>Thu</day>
     <day>Fri</day>
</Days>

2 个答案:

答案 0 :(得分:0)

试试这个:

  File file = new File("YourXMLFile.xml");
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse(file);
  doc.getDocumentElement().normalize();
  NodeList nodeLst = doc.getElementsByTagName("days");

  if (nodeLst.getLenth() > 1) {
     String first = ((Node) nodeLst.item(s)).getNodeValue().toString().toUpperCase();
     String last = ((Node) nodeLst.item(nodeLst.getLength() - 1)).getNodeValue().toString().toUpperCase();
     System.out.println(first + "-" + last);
  }

答案 1 :(得分:0)

在这里,您将使用xstream库进行示例:

package MonFri.monfri;

import java.util.List;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;


public class App 
{
@SuppressWarnings("unchecked")
public static void main( String[] args )
{

    XStream xstream = new XStream(new DomDriver());
    xstream.alias("day", String.class);
    xstream.alias("Days", List.class);
    List<String> days = (List<String>)xstream.fromXML(data);
    String firstDay = days.get(0);
    String lastDay = days.get(days.size()-1);
    System.out.println(firstDay.toUpperCase() + "-" + lastDay.toUpperCase());
}
private static String data = "<Days>\n" + 
        "    <day>Mon</day>\n" + 
        "     <day>Tue</day>\n" + 
        "     <day>Wed</day>\n" + 
        "     <day>Thu</day>\n" + 
        "     <day>Fri</day>\n" + 
        "</Days>";
}

打印MON-FRI

希望有所帮助