我正在尝试编写一个代码来帮助我创建一个 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 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!