2014-12-18 25 views
6

Benxml hashmap nasıl ayrıştırılır?

<?xml version="1.0" encoding="utf-8"?> 

<Details> 
    <detail-a> 

     <detail> attribute 1 of detail a </detail> 
     <detail> attribute 2 of detail a </detail> 
     <detail> attribute 3 of detail a </detail> 

    </detail-a> 

    <detail-b> 
     <detail> attribute 1 of detail b </detail> 
     <detail> attribute 2 of detail b </detail> 

    </detail-b> 


</Details> 

Ben anahtar bir dize ve bir değerdir hashmap bunu ayrıştırmak olacak bir yöntem yazmak için bu xml den istiyoruz ayrıştırmak istediğiniz bir xml bir örnek var dizeleri listesidir .

Örneğin

: anahtar "detay" değeri = { "A detayının özelliği, 1", "A detayının özelliği, 2", "A detayının özelliği, 3"} böylece

ve ..

Bunu yapmanın en iyi yolu nedir? Kafam karıştı, çünkü:

\ ı bu kadar detay a ve detay-b yazdırmak için denemek lazım ama

public static void main(String[] args) { 
    // TODO Auto-generated method stub 

    DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); 

     DocumentBuilder builder; 
     try { 
      builder = factory.newDocumentBuilder(); 
      File f= new File("src/Details.xml"); 
      Document doc=builder.parse(f); 
      Element root=doc.getDocumentElement(); 
      NodeList children=root.getChildNodes(); 
      for(int i=0;i<children.getLength();i++) 
      { 
       Node child=children.item(i); 
       if (child instanceof Element) 
       { 
        Element childElement=(Element) child; 
        Text textNode=(Text)childElement.getFirstChild(); 
        String text=textNode.getData().trim(); 
        System.out.println(text); 

       } 
      } 

     } catch (ParserConfigurationException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 
     } catch (SAXException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
+0

Bir şey denediniz mi? –

+0

XStream yararlı olacak – sol4me

+0

bir dize içine xml dönüştürebilirsiniz ve sonra bir hashmap içinde tutabilirsiniz –

cevap

3

Kullanım JAXBxml okunan ve bir kaydetmek için ... boş olsun özel nesne.

Özel nesne sınıfı:

import java.util.List; 

import javax.xml.bind.annotation.XmlElement; 
import javax.xml.bind.annotation.XmlElementWrapper; 
import javax.xml.bind.annotation.XmlRootElement; 
import javax.xml.bind.annotation.XmlType; 

@XmlRootElement(name = "Details") 
@XmlType(propOrder = { "detailA", "detailB" }) 
public class Details { 
    private List<String> detailA; 
    private List<String> detailB; 

    public void setDetailA(List<String> detailA) { 
     this.detailA = detailA; 
    } 

    @XmlElementWrapper(name = "detail-a") 
    @XmlElement(name = "detail") 
    public List<String> getDetailA() { 
     return detailA; 
    } 

    public void setDetailB(List<String> detailB) { 
     this.detailB = detailB; 
    } 

    @XmlElementWrapper(name = "detail-b") 
    @XmlElement(name = "detail") 
    public List<String> getDetailB() { 
     return detailB; 
    } 
} 

sonra, nesneye içine xml verileri Özü istendiği gibi bir haritaya içeriğini ekleyin:

public static void main(String[] args) throws JAXBException, FileNotFoundException { 
    System.out.println("Output from our XML File: "); 
    JAXBContext context = JAXBContext.newInstance(Details.class); 
    Unmarshaller um = context.createUnmarshaller(); 
    Details details = (Details)um.unmarshal(new FileReader("details.xml")); 
    List<String> detailA = details.getDetailA(); 
    List<String> detailB = details.getDetailB(); 

    Map<String, String[]> map = new HashMap<String, String[]>(); 
    map.put("detail-a", detailA.toArray(new String[detailA.size()])); 
    map.put("detail-b", detailB.toArray(new String[detailB.size()])); 


    for (Map.Entry<String, String[]> entry : map.entrySet()) { 
     //key "detail a" value={"attribute 1 of detail a","attribute 2 of detail a","attribute 3 of detail a"} 
     System.out.print("Key \"" +entry.getKey()+"\" value={"); 
     for(int i=0;i<entry.getValue().length;i++){ 
      if(i!=entry.getValue().length-1){ 
       System.out.print("\""+entry.getValue()[i]+"\","); 
      } 
      else{ 
       System.out.print("\""+entry.getValue()[i]+"\"}"); 
      } 
     } 
     System.out.println(); 
    } 
} 

Çıktı olacaktır:

 
Output from our XML File: 
Key "detail-a" value={"attribute 1 of detail a","attribute 2 of detail a","attribute 3 of detail a"} 
Key "detail-b" value={"attribute 1 of detail b","attribute 2 of detail b"} 

Bir not olarak: Bu, daha fazla ayrıntı eklemeniz gerekiyorsa, sorunuzda girdi olarak sağladığınız xml için çalışır detail-c gibi ve böylece bunları özel nesnenizde tanımlamanız gerekir. kullanılan

XML:

<?xml version="1.0" encoding="utf-8"?> 
<Details> 
    <detail-a> 
     <detail>attribute 1 of detail a</detail> 
     <detail>attribute 2 of detail a</detail> 
     <detail>attribute 3 of detail a</detail> 
    </detail-a> 
    <detail-b> 
     <detail>attribute 1 of detail b</detail> 
     <detail>attribute 2 of detail b</detail> 
    </detail-b> 
</Details> 
2

ben "detay x", alt elemanlara herhangi bir sayı ile çalışır XMLBeam kullanarak çok daha kısa bir çözüm sunmak için duramazlar.

public class Tetst { 

@XBDocURL("resource://test.xml") 
public interface Projection { 
    @XBRead("name()") 
    String getName(); 

    @XBRead("./detail") 
    List<String> getDetailStrings(); 

    @XBRead("/Details/*") 
    List<Projection> getDetails(); 
} 

@Test 
public void xml2Hashmap() throws IOException { 
    HashMap<String, List<String>> hashmap = new HashMap<String, List<String>>(); 
    for (Projection p : new XBProjector().io().fromURLAnnotation(Projection.class).getDetails()) { 
     System.out.println(p.getName() + ": " + p.getDetailStrings()); 
     hashmap.put(p.getName(), p.getDetailStrings()); 
    } 
} 
} 

Bu örnek Test.xml için

detail-a: [ attribute 1 of detail a , attribute 2 of detail a , attribute 3 of detail a ] 
detail-b: [ attribute 1 of detail b , attribute 2 of detail b ] 

yazdırır ve bir HashMap doldurur.

İlgili konular