我编写了一个 Twitter 桌面应用程序,基本上只是让我发布推文和图片......没什么花哨的。
我已经完成了所有工作,但保留配置文件的最后一部分(这是我的应用程序生成的以下 XML。
<?xml version="1.0" encoding="UTF-8" standalone="no"?><Twitterer><config id="1"><accessToken>ENDLESS-STRING-OF-CHARACTERS</accessToken><accessTokenSecret>ANOTHER-ENDLESS-STRING-OF-CHARACTERS</accessTokenSecret></config></Twitterer>
我需要做的只是设置 accessToken 和 accessTokenSecret 变量。文件名是config.xml。
我一直在网上查看很多示例,但似乎无法集中注意力只从文件中获取两个值,这不需要循环。
这就是我对最后一 block 拼图的了解:
try {
File fXmlFile = new File(this.getFileName());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
NodeList nList = doc.getElementsByTagName("config");
int numberOfConfigs = nList.getLength();
// GET THE TWO VARIABLES HERE
} catch (Exception e) {
}
如果有人可以帮助我将这两个标签读入相应的变量中,我将非常感激。之后我可以处理其余的授权。
最佳答案
What I need to do is just set the accessToken & accessTokenSecret variables
使用getElementsByTagName()
方法的简单代码
Element root = doc.getDocumentElement();
root.getElementsByTagName("accessToken").item(0).getTextContent()
root.getElementsByTagName("accessTokenSecret").item(0).getTextContent()
输出:
ENDLESS-STRING-OF-CHARACTERS
ANOTHER-ENDLESS-STRING-OF-CHARACTERS
<小时/>
或者尝试作为 config
标记的子节点
Element root = doc.getDocumentElement();
NodeList configNodeList = root.getElementsByTagName("config");
NodeList nodeList = ((Node) configNodeList.item(0)).getChildNodes();
System.out.println(nodeList.item(0).getTextContent());
System.out.println(nodeList.item(1).getTextContent());
关于java - 需要帮助解析 Twitter Oauth 的 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25147392/