問題描述
我正在嘗試編寫一個代碼來幫助我創建一個 XML 對象.例如,我將一個字符串作為函數的輸入,它會返回一個 XMLObject.
I am trying to write a code that helps me to create a XML object. For example, I will give a string as input to a function and it will return me a XMLObject.
XMLObject convertToXML(String s) {}
當我在網上搜索時,我通常會看到有關創建 XML 文檔的示例.所以我看到的所有關于創建 XML 并寫入文件并創建文件的事情.但我做過類似的事情:
When I was searching on the net, generally I saw examples about creating XML documents. So all the things I saw about creating an XML and write on to a file and create the file. But I have done something like that:
Document document = new Document();
Element child = new Element("snmp");
child.addContent(new Element("snmpType").setText("snmpget"));
child.addContent(new Element("IpAdress").setText("127.0.0.1"));
child.addContent(new Element("OID").setText("1.3.6.1.2.1.1.3.0"));
document.setContent(child);
您認為創建一個 XML 對象就足夠了嗎?你能幫我如何從 XML 中獲取數據嗎?例如,如何從該 XML 中獲取 IpAdress
?
Do you think it is enough to create an XML object? and also can you please help me how to get data from XML? For example, how can I get the IpAdress
from that XML?
非常感謝大家
編輯 1: 實際上,現在我認為擁有一個像 base.xml
這樣的文件對我來說可能會容易得多,我會將所有基本內容寫入其中例如:
EDIT 1: Actually now I thought that maybe it would be much easier for me to have a file like base.xml
, I will write all basic things into that for example:
<snmp>
<snmpType><snmpType>
<OID></OID>
</snmp>
然后使用這個文件創建一個 XML 對象.你怎么看?
and then use this file to create a XML object. What do you think about that?
推薦答案
如果您可以創建字符串 xml,您可以輕松地將其轉換為 xml 文檔對象,例如-
If you can create a string xml you can easily transform it to the xml document object e.g. -
String xmlString = "<?xml version="1.0" encoding="utf-8"?><a><b></b><c></c></a>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try {
builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(xmlString)));
} catch (Exception e) {
e.printStackTrace();
}
您可以使用文檔對象和xml解析庫或xpath來取回ip地址.
You can use the document object and xml parsing libraries or xpath to get back the ip address.
這篇關于如何在 Java 中從 String 創建 XML 對象?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!