我有以下代码:
<ishfields>
<ishfield name="FTITLE" level="logical">3* Family map</ishfield>
<ishfield name="FDESCRIPTION" level="logical">111</ishfield>
<ishfield name="FCHANGES" level="version" />
</ishfields>
我想获得字段名称=&#34; FDESCRIPTION&#34;的文本内容。
我甚至无法获取内容111.
我使用了getelementsbytagname()和许多方法。任何人都可以帮忙怎么做? 这是我的java代码:
try {
String file="E:\\Repository\\17Nov_demo\\file.xml";
DocumentBuilderFactory documentbuilderfactory=DocumentBuilderFactory.newInstance();
DocumentBuilder documentbuilder =documentbuilderfactory.newDocumentBuilder();
Document doc=documentbuilder.parse(file);
Element element=doc.getDocumentElement();
NodeList nodelist=element.getChildNodes();
for (int i = 0; i < nodelist.getLength(); i++) {
System.out.println(nodelist);
}
}
catch(Exception e)
{
}
我知道它只会获取整个文档节点。但我无法理解如何使用xpath或其他任何方式去特定节点。请帮助!!
答案 0 :(得分:0)
如果你使用Xml做很多事情,那么更喜欢xPath而不是本机代码。
要检索您的数据,您只需要这样做:
// ishfield [@name =&#34; FDESCRIPTION&#34;] /文本()
你可以在这里测试:
http://www.xpathtester.com/xpath/7f3c6f31096fbb33c728ca3e6216fd41
Gegko
答案 1 :(得分:0)
您可以使用JAXB
。您可以看到JAXB
是here的内容。
现在你必须在java中指定ishfields
类,例如:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="ishfields")
class Ishfields{
List<Ishfield> fields;
}
当然是Ishfield
类:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="ishfield")
class Ishfield{
@XmlAttribute
String name;
@XmlAttribute
String level;
}
现在在Main
课程中你可以试试这个:
import java.io.FileReader;
import java.util.List;
import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
//those are the all the imports you need. You can import all of them in Main if you also put here the two classes as inner.
public class Main {
public static void main(String[] args) throws Exception {
Ishfields i = JAXB.unmarshal(new FileReader("yourXml.xml"), Ishfields.class);
System.out.println(r);
JAXB.marshal(r, System.out);
}
}
此外,您还可以使用生成的对象执行任何操作。
您可以获得价值,名称,等级等。我认为你的xml
在一个文件中。如果您的xml
是String
,那么当然可以做同样的事情。