【问题标题】:How to set keys and values of a hashmap as tags and values of a xml file如何将哈希图的键和值设置为 xml 文件的标签和值
【发布时间】:2013-09-15 12:10:27
【问题描述】:

我关注http://blog.bdoughan.com/2013/06/moxys-xmlvariablenode-using-maps-key-as.html,我的代码如下写了

请求和响应 XML

<AlphabetReq>
    <a>Apple</a>
    <b>Ball</b>
    <c>Cat</c> 
    <d>Dog</d>
    <e>Elephant</e>
    <f>Fox</f>
</AlphabetReq>

<AlphabetResp>
    <a>Apple</a>
    <b>Ball</b>
    <c>Cat</c> 
    <d>Dog</d>
    <e>Elephant</e>
    <f>Fox</f>
</AlphabetResp>

AlphabetReq 和 AlphabetResp 类

import java.util.LinkedHashMap;
import java.util.Map.Entry;
import java.util.Set;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.eclipse.persistence.oxm.annotations.XmlPath;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Alph {

@XmlPath(".")
@XmlJavaTypeAdapter(AlphAdapter.class)
private LinkedHashMap<String, String> cLinkedHashMap = new 
        LinkedHashMap<String, String>();

@XmlPath(".")
@XmlJavaTypeAdapter(AlphAdapter.class)
private LinkedHashMap<String, String> gLinkedHashMap = new 
        LinkedHashMap<String, String>();

protected void put(String theKey, String theValue) {
    cLinkedHashMap.put(theKey, theValue);   
    gLinkedHashMap.put(theKey, theValue);
}

protected String get(String theKey) {
    return (String) cLinkedHashMap.get(theKey);
}

protected Set<Entry<String,String>> getCEntrySet() {
    return cLinkedHashMap.entrySet();
}

protected Set<Entry<String,String>> getGEntrySet() {
    return gLinkedHashMap.entrySet();
}

protected LinkedHashMap<String, String> getCLinkedHashMap() {
    return cLinkedHashMap;
}

protected LinkedHashMap<String, String> getGLinkedHashMap() {
    return gLinkedHashMap;
}

public String toCXML() throws XMLHandlingException {
    return null;
}

public String toGXML() throws XMLHandlingException {
    return null;
}

}

@XmlRootElement(name="AlphReq")
@XmlDiscriminatorValue("AlphabetReq")
@XmlAccessorType(XmlAccessType.FIELD)
public class AlphabetReq extends Alph {

public static AlphabetReq getInstance(String theAlphabetReqXML) throws 
XMLHandlingException {
    return XMLUtils.parseAlphabetReqXML(theAlphabetReqXML);
}

public String toCXML() throws XMLHandlingException {
    return XMLUtils.getAlphabetReqXML(this);
}

}

@XmlRootElement(name="AlphResp")
@XmlDiscriminatorValue("AlphabetResp")
@XmlAccessorType(XmlAccessType.FIELD)
public class AlphabetResp extends Alph {

public static AlphabetResp getInstance(String theAlphabetRespXML) throws 
XMLHandlingException {
    return XMLUtils.parseAlphabetRespXML(theAlphabetRespXML);
}

public String toCXML() throws XMLHandlingException {
    return XMLUtils.getAlphabetRespXML(this);
}

}

我创建了以下用于编组和解组的 XMLUtil 方法

public static String getAlphabetReqXML(Alph theAlphabet) throws XMLHandlingException {

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Writer writer = null;

try {
    writer = new OutputStreamWriter(byteArrayOutputStream, "UTF-8");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

try {
    writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" );
} catch (IOException e) {
    e.printStackTrace();
}

try {
    JAXBContext JContext = JAXBContext.newInstance(AlphabetReq.class); 
    Marshaller JMarshaller = JContext.createMarshaller();
    JMarshaller.marshal(theAlphabet, writer);
} catch (Throwable e) {
    e.printStackTrace();
}

String theAlphabetReqXML = byteArrayOutputStream.toString();
return theAlphabetReqXML;

}

public static AlphabetReq parseAlphabetReqXML(String theAlphabetReqXML) throws 
XMLHandlingException {

if(null == theAlphabetReqXML) {
    return null;
}
try {
    InputStream IPStream = new ByteArrayInputStream(theAlphabetReqXML.getBytes());
    JAXBContext JContext = JAXBContext.newInstance(AlphabetReq.class);
    Unmarshaller JUnmarshaller = JContext.createUnmarshaller();
    AlphabetReq alphabetreq = (AlphabetReq) JUnmarshaller.unmarshal(IPStream);
    return alphabetreq;
} catch(Throwable t) {
    t.printStackTrace();
}
}

public static String getAlphabetRespXML(Alph theAlphabet) throws XMLHandlingException {

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Writer writer = null;

try {
    writer = new OutputStreamWriter(byteArrayOutputStream, "UTF-8");
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

try {
    writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" );
} catch (IOException e) {
    e.printStackTrace();
}

try {
    JAXBContext JContext = JAXBContext.newInstance(AlphabetResp.class); 
    Marshaller JMarshaller = JContext.createMarshaller();
    JMarshaller.marshal(theAlphabet, writer);
} catch (Throwable e) {
    e.printStackTrace();
}

String theAlphabetRespXML = byteArrayOutputStream.toString();
return theAlphabetRespXML;

}

public static AlphabetResp parseAlphabetReqXML(String theAlphabetRespXML) throws 
XMLHandlingException {

if(null == theAlphabetRespXML) {
    return null;
}
try {
    InputStream IPStream = new ByteArrayInputStream(theAlphabetRespXML.getBytes());
    JAXBContext JContext = JAXBContext.newInstance(AlphabetResp.class);
    Unmarshaller JUnmarshaller = JContext.createUnmarshaller();
    AlphabetResp alphabetresp = (AlphabetResp) JUnmarshaller.unmarshal(IPStream);
    return alphabetresp;
} catch(Throwable t) {
    t.printStackTrace();
}
}

并引入了一个适配器类

import java.util.*;
import java.util.Map.Entry;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.eclipse.persistence.oxm.annotations.XmlVariableNode;

public class AlphAdapter extends XmlAdapter<AlphAdapter.AdaptedMap, LinkedHashMap<String, String>>{

public static class AdaptedMap {
    @XmlVariableNode("key")
    List<AdaptedEntry> entries = new ArrayList<AdaptedEntry>();  
}

public static class AdaptedEntry {  
    @XmlTransient
    public String key;

    @XmlValue
    public String value;
}

@Override
public AdaptedMap marshal(LinkedHashMap<String, String> map) throws Exception {
    AdaptedMap adaptedMap = new AdaptedMap();
    for(Entry<String, String> entry : map.entrySet()) {
        AdaptedEntry adaptedEntry = new AdaptedEntry();
        adaptedEntry.key = entry.getKey();
        adaptedEntry.value = entry.getValue();
        adaptedMap.entries.add(adaptedEntry);
    }
    return adaptedMap;
}

@Override
public LinkedHashMap<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
    List<AdaptedEntry> adaptedEntries = adaptedMap.entries;
    LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(adaptedEntries.size());
    for(AdaptedEntry adaptedEntry : adaptedMap.entries) {
        map.put(adaptedEntry.key, adaptedEntry.value);
    }
    return map;
}
}

当我运行它时,我没有在我的adaptedmap 中获得任何值。它有键但值为空

例如:

  • 键:A,值:空
  • 键:B,值:空
  • 键:C,值:空
  • 键:D,值:空
  • 键:E,值:空
  • 键:F,值:空

感谢任何帮助。

谢谢

【问题讨论】:

    标签: java xml jaxb eclipselink


    【解决方案1】:

    TL;DR

    问题是您试图将 use 元素名称用作同一级别的两个地图的关键技巧。这导致了您的问题。

    @XmlPath(".")
    @XmlJavaTypeAdapter(AlphAdapter.class)
    private LinkedHashMap<String, String> cLinkedHashMap = new 
            LinkedHashMap<String, String>();
    
    @XmlPath(".")
    @XmlJavaTypeAdapter(AlphAdapter.class)
    private LinkedHashMap<String, String> gLinkedHashMap = new 
            LinkedHashMap<String, String>();
    

    下面是你的东西目前的工作方式

    演示代码

    import java.io.File;
    import javax.xml.bind.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(AlphabetReq.class, AlphabetResp.class);
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            File xml = new File("src/forum18741690/input.xml");
            AlphabetReq ar = (AlphabetReq) unmarshaller.unmarshal(xml);
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(ar, System.out);
        }
    
    }
    

    输出

    <?xml version="1.0" encoding="UTF-8"?>
    <AlphReq xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="AlphabetReq">
       <a/>
       <b/>
       <c/>
       <d/>
       <e/>
       <f/>
       <a>Apple</a>
       <b>Ball</b>
       <c>Cat</c>
       <d>Dog</d>
       <e>Elephant</e>
       <f>Fox</f>
    </AlphReq>
    

    【讨论】:

    • 您好@BlaiseDoughan,我们需要第二个linkedhashmap 来记录敏感数据。有什么方法可以用两个链接的哈希图完成。任何帮助表示赞赏。
    【解决方案2】:

    您可以改用@XmlAnyElement

    @XmlAccessorType(XmlAccessType.FIELD)
    public class AlphabetReq 
    {
       @XmlAnyElement
       private List<Element> allTags = new ArrayList<Element>();
    
       List<Element> getAllTags()
       {
          return allTags;
       }
    
       void setAllTags(List<Element> allTags)
       {
          this.allTags = allTags;
       }
    
       public Map<String, String> getValues()
       {
          final Map<String, String> retVal = new HashMap<String, String>();
          for (Element el : allTags)
          {
             retVal.put(el.getNodeName(), el.getTextContent());
          }
          return retVal;
       }
    }  
    

    方法GetValues()按预期返回值:

    {f=Fox, d=Dog, e=Elephant, b=Ball, c=Cat, a=Apple}  
    

    示例:

      AlphabetReq obj = JAXB.unmarshal(new java.io.File("D:/test.xml"), AlphabetReq.class);
      System.out.println(obj.getValues());
      JAXB.marshal(obj, System.out);
    

    【讨论】:

    • 你好@Ilya,这对我不起作用我得到相同的空值结果。
    猜你喜欢
    • 2015-11-12
    • 2021-12-15
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多