簡體   English   中英

使用 Apache XMLBeans 在字符串中編碼 XML 實體

[英]Encoding XML entities in string using Apache XMLBeans

我想使用 Apache XMLBeans 來轉義字符串以將其嵌入到 XML 文檔中,例如編碼所有 XML 實體。

XmlString 確實提供了此功能,但堅持將 output 包裝在 xml-fragment 標記中,我想擺脫它。

但是,我對建議不感興趣

  • 使用 XMLBeans 以外的任何東西(如 org.apache.commons.lang.StringEscapeUtils)
  • 在 escaping 之后刪除封閉標簽(例如使用正則表達式)

這是一個測試用例。 你能幫我修一下嗎?

import org.apache.xmlbeans.*;

public class Test {
  @Test public void test(){
    String input = "You & me";
    String expected = "You & me";
    String actual = escape(input);
    Assert.assertEquals(expected, actual);
    // Fails with: ComparisonFailure: expected:<[You &amp; me]> 
    //             but was:<[<xml-fragment>You &amp; me</xml-fragment>]>
  }

  private String escape(String str){
    XmlString value = XmlString.Factory.newInstance();
    value.setStringValue(input);
    XmlOptions opts = new XmlOptions();
    // do I need to set one of the 54 available options?
    // see http://xmlbeans.apache.org/docs/2.4.0/reference/org/apache/xmlbeans/XmlOptions.html
    return value.xmlText(opts);
  }
}

在將 XmlOptions 傳遞給 xmlText() 方法之前使用 setSaveOuter() 選項。 像這樣。

XmlOptions opts = new XmlOptions();
opts.setSaveOuter();
return value.xmlText(opts);

我想澄清一下,如果你只是憑空創建一個新元素,似乎元素名稱不會被序列化。 例如,如果我有一個 Model 元素,上面有一個 Property 元素,則以下不會顯示屬性標簽,它將顯示 xml 片段。

Property property = Property.Factory.newInstance(); 

XmlOptions opts = new XmlOptions();
opts.setSaveOuter();
return property.xmlText(opts);

要顯示屬性元素,我必須執行以下操作。

ModelDocument modelDoc = ModelDocument.Factory.newInstance();
ModelType model = modelDoc.addNewModel();
PropertyType propertyType = model.addNewProperty();
Property property = Property.Factory.newInstance(); 

XmlOptions opts = new XmlOptions();
opts.setSaveOuter();
return property.xmlText(opts);

您預期的字符串不正確。 通過調用 xmlText,它將返回一個 XML,因此該字符串必須包裝在 xml-fragment 元素中。

創建 xml 閱讀器作為普通的 xml 字符串然后刪除 xml 片段,我試過這樣,

if(request != null && request.contains("<xml")){
XMLInputFactory xif = XMLInputFactory.newFactory();
StringReader reader = new StringReader(request);
StreamSource xml = new StreamSource(reader);
XMLStreamReader xsr = xif.createXMLStreamReader(xml);
xsr.nextTag();          
request = xsr.getElementText();
System.out.println("updated request is \n"+request);
}

然后

JAXBContext jaxbContext = JAXBContext.newInstance(YourClass.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(request);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM