問題描述
我需要 unmarshall
未知 XML
內(nèi)容的子集,使用該未編組的對象,我需要修改一些內(nèi)容并重新綁定相同的 XML 內(nèi)容(子集) 與原始 XML.
I have a requirement to unmarshall
a subset of Unknown XML
content, with that unmarshalled object, I need modify some contents and re-bind the same XML content(subset) with the Original XML.
輸入 XML 示例:
<Message>
<x>
</x>
<y>
</y>
<z>
</z>
<!-- Need to unmarshall this content to "Content" - java Object -->
<Content>
<Name>Robin</Name>
<Role>SM</Role>
<Status>Active</Status>
</Content>
.....
</Message>
需要單獨解組 <Content>
標記,保持其他 XML 部分相同.需要修改<Content>
標簽中的元素,并將修改后的XML部分與原文綁定,如下圖:
Need to unmarshall the <Content>
tag alone, by keeping the other XML part as same. Need to modify the elements in <Content>
tag and bind the modified XML part with the original as shown below:
預(yù)期輸出 XML:
<Message>
<x>
</x>
<y>
</y>
<z>
</z>
<!-- Need to unmarshall this content to "Content" - java Object -->
<Content>
<Name>Robin_123</Name>
<Role>Senior Member</Role>
<Status>1</Status>
</Content>
.....
</Message>
我的問題:
此要求的可能解決方案是什么?(除了
DOM
解析 - 因為 XML 網(wǎng)絡(luò)非常龐大)
What is the possible solution for this Requirement ? (Except
DOM
parsing - as XML contnet is very huge)
JAXB2.0
中是否有任何選項可以執(zhí)行此操作?
Is there any option to do this in JAXB2.0
?
請就此提出您的建議.
推薦答案
考慮使用 StAX API.
對于給定的示例,此代碼使用 Content
元素的根元素創(chuàng)建一個 DOM 文檔:
For the given sample, this code creates a DOM document with a root element of the Content
element:
class ContentFinder implements StreamFilter {
private boolean capture = false;
@Override public boolean accept(XMLStreamReader xml) {
if (xml.isStartElement() && "Content".equals(xml.getLocalName())) {
capture = true;
} else if (xml.isEndElement() && "Content".equals(xml.getLocalName())) {
capture = false;
return true;
}
return capture;
}
}
XMLInputFactory inFactory = XMLInputFactory.newFactory();
XMLStreamReader reader = inFactory.createXMLStreamReader(inputStream);
reader = inFactory.createFilteredReader(reader, new ContentFinder());
Source src = new StAXSource(reader);
DOMResult res = new DOMResult();
TransformerFactory.newInstance().newTransformer().transform(src, res);
Document doc = (Document) res.getNode();
這可以是 作為 /transform/dom/DOMSource.html" rel="nofollow">DOMSource.
This can then be passed to JAXB as a DOMSource.
在輸出時重寫 XML 時可以使用類似的技術(shù).
Similar techniques can be used when rewriting the XML on output.
JAXB 似乎不直接接受 StreamSource
,至少在 Oracle 1.7 實現(xiàn)中是這樣.
JAXB doesn't seem to accept a StreamSource
directly, at least in the Oracle 1.7 implementation.
這篇關(guān)于JAXB 解組未知 XML 內(nèi)容的子集的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!