【问题标题】:how to get the text content for xml如何获取xml的文本内容
【发布时间】:2017-03-31 18:36:00
【问题描述】:

我有以下代码:

<ishfields>
    <ishfield name="FTITLE" level="logical">3* Family map</ishfield>
    <ishfield name="FDESCRIPTION" level="logical">111</ishfield>
    <ishfield name="FCHANGES" level="version" />
</ishfields>

我想获取字段名=“FDESCRIPTION”的文本内容。

我什至无法获取内容 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 或其他方式去那个特定的节点。请帮忙!!

【问题讨论】:

标签: java xml dom xmldocument


【解决方案1】:

您可以使用JAXB。你可以看到JAXBhere

现在您必须在 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 在文件中。如果你的xmlString,当然有办法做同样的事情。

【讨论】:

    【解决方案2】:

    如果您使用 Xml 做很多事情,首选 xPath 比原生代码更具可读性。

    而要检索您的数据,您只需要这样做:

    //ishfield[@name="FDESCRIPTION"]/text()

    你可以在这里测试:

    http://www.xpathtester.com/xpath/7f3c6f31096fbb33c728ca3e6216fd41

    壁虎

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-20
      • 2011-05-27
      • 2013-06-01
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      • 2012-12-03
      • 2020-11-05
      相关资源
      最近更新 更多