如何在 Java 中从 String 创建 XML 对象?
我正在尝试编写一段代码来帮助我创建 XML 对象。例如,我将提供一个字符串作为函数的输入,它将返回一个 XMLObject。
XMLObject convertToXML(String s) {}
当我在网上搜索时,通常会看到有关创建XML文档的示例。我所看到的所有关于创建 XML、写入文件并创建文件的内容。但我做了类似的事情:
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
?
非常感谢大家
编辑1:实际上现在我想也许对我来说拥有一个像base.xml
这样的文件会更容易,我会写所有基本的东西例如:
<snmp>
<snmpType><snmpType>
<OID></OID>
</snmp>
然后使用此文件创建 XML 对象。你对此有何看法?
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) {}
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);
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?
Thank you all a lot
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>
and then use this file to create a XML object. What do you think about that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您可以创建一个字符串 xml,您可以轻松地将其转换为 xml 文档对象,例如 -
您可以使用文档对象和 xml 解析库或 xpath 来获取 IP 地址。
If you can create a string xml you can easily transform it to the xml document object e.g. -
You can use the document object and xml parsing libraries or xpath to get back the ip address.
尝试类似的东西
try something like