21

私は次のようなxmlを持っています:

{ <xml><ep><source type="xml">...</source><source type="text">..</source></ep></xml>}

ここで、タイプが属性である「ソースタイプ」の値を取得したいと思います。

私はこのように試しましたが、うまくいきません:

 DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
                try {
                    DocumentBuilder builder = domFactory.newDocumentBuilder();
                    Document dDoc = builder.parse("D:/workspace1/ereader/src/main/webapp/configurations/config.xml");
                    System.out.println(dDoc);
                    XPath xPath = XPathFactory.newInstance().newXPath();
                    Node node = (Node) xPath.evaluate("//xml/source/@type/text()", dDoc, XPathConstants.NODE);
                    System.out.println(node);
                } catch (Exception e) {
                    e.printStackTrace();

私もこれを試しました:

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader("config.xml"));
            Document doc = builder.parse(is);

            NodeList nodeList = doc.getElementsByTagName("source");

            for (int i = 0; i < nodeList.getLength(); i++) {                
                Node node = nodeList.item(i);

                if (node.hasAttributes()) {
                    Attr attr = (Attr) node.getAttributes().getNamedItem("type");
                    if (attr != null) {
                        String attribute= attr.getValue();                      
                        System.out.println("attribute: " + attribute);                      
                    }
                }
            }

助けてください!!

前もってありがとう、ヴァルシャ。

4

7 に答える 7

32

あなたの質問はより一般的であるため、Java で利用可能な XML パーサーを使用して実装してみてください。パーサーに固有に必要な場合は、ここでコードを更新してください。

<?xml version="1.0" encoding="UTF-8"?>
<ep>
    <source type="xml">TEST</source>
    <source type="text"></source>
</ep>
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse("uri to xmlfile");
XPathFactory xPathfactory = XPathFactory.newInstance();
XPath xpath = xPathfactory.newXPath();
XPathExpression expr = xpath.compile("//ep/source[@type]");
NodeList nl = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);

for (int i = 0; i < nl.getLength(); i++)
{
    Node currentItem = nl.item(i);
    String key = currentItem.getAttributes().getNamedItem("type").getNodeValue();
    System.out.println(key);
}
于 2012-08-08T11:15:05.667 に答える
4

このようなことを試してください:

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dDoc = builder.parse("d://utf8test.xml");

    XPath xPath = XPathFactory.newInstance().newXPath();
    NodeList nodes = (NodeList) xPath.evaluate("//xml/ep/source/@type", dDoc, XPathConstants.NODESET);
    for (int i = 0; i < nodes.getLength(); i++) {
        Node node = nodes.item(i);
        System.out.println(node.getTextContent());
    }

変更点に注意してください:

  • 単一のノードだけでなく、ノードセット (XPathConstants.NODESET) も要求します。
  • xpath は //xml/ep/source/@type になり、//xml/source/@type/text() ではなくなりました

PS: タグ java を質問に追加できますか? ありがとう。

于 2012-08-08T14:53:12.920 に答える
1

以下は、VTD-XMLでそれを行うコードです。

import com.ximpleware.*;

public class queryAttr{
     public static void main(String[] s) throws VTDException{
         VTDGen vg= new VTDGen();
         if (!vg.parseFile("input.xml", false))
            return false;
         VTDNav vn = vg.getNav();
         AutoPilot ap = new AutoPilot(vn);
         ap.selectXPath("//xml/ep/source/@type");
         int i=0;
         while((i = ap.evalXPath())!=-1){
               system.out.println(" attr val ===>"+ vn.toString(i+1));

         }
     }
}
于 2016-04-26T00:25:40.423 に答える
1

このスニペットが正常に機能することをうれしく思います。

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(new File("config.xml"));
NodeList nodeList = document.getElementsByTagName("source");
for(int x=0,size= nodeList.getLength(); x<size; x++) {
    System.out.println(nodeList.item(x).getAttributes().getNamedItem("type").getNodeValue());
} 
于 2012-08-09T05:00:43.697 に答える
1

使用する

document.getElementsByTagName(" * ");

XML ファイル内からすべての XML 要素を取得するには、繰り返し属性を返します。

例:

NodeList list = doc.getElementsByTagName("*");


System.out.println("XML 要素: ");

        for (int i=0; i<list.getLength(); i++) {

            Element element = (Element)list.item(i);
            System.out.println(element.getNodeName());
        }
于 2014-12-22T13:49:39.630 に答える
0
public static void main(String[] args) throws IOException {
    String filePath = "/Users/myXml/VH181.xml";
    File xmlFile = new File(filePath);
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder;
    try {
        dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();
        printElement(doc);
        System.out.println("XML file updated successfully");
    } catch (SAXException | ParserConfigurationException e1) {
        e1.printStackTrace();
    }
}
private static void printElement(Document someNode) {
    NodeList nodeList = someNode.getElementsByTagName("choiceInteraction");
    for(int z=0,size= nodeList.getLength();z<size; z++) {
            String Value = nodeList.item(z).getAttributes().getNamedItem("id").getNodeValue();
            System.out.println("Choice Interaction Id:"+Value);
        }
    }

メソッドを使用してこのコードを試すことができます

于 2016-02-09T13:41:54.160 に答える
0

以下は、ルート Document オブジェクトと特定の XPATH から任意のノードの値を取得するために作成したユーティリティ メソッドです。

public String getValue(Document doc, String xPath) throws Exception {
   XPathFactory factory = XPathFactory.newInstance();
   XPath path = factory.newXPath();
   XPathExpression expression = path.compile(xPath);
   Node node = (Node) expression.evaluate(doc,XPathConstants.NODE);
   return node.getFirstChild().getNodeValue();
}

すべてのライブラリーは、java.xml.xpathおよび org.w3c.dom からのものです。

これで、ルート ドキュメント要素と正しいパスが必要になります。あなたの例では、/ep/source/@type

したがって、基本的に XPath は、目的の要素までナビゲートし、その後に関心のある/@attributeNameが続きます。

node /ep/source@typeは機能しません。(これのトラブルシューティングに 30 分無駄にしました)。

于 2021-09-10T09:04:18.153 に答える