繁体   English   中英

Java:如何从Java中的xml获取属性名称?(JDOM)

[英]Java:How to get Attribute name from xml in Java?(JDOM)

Java:如何使用JAVA-JDOM获取节点的属性名称? 例如,

<xml>
    <Test id="001"></Test>
</xml>

输出应为:

id

我的Java程序:在______中需要获取源文件中的节点的属性名称。 该程序只将“ _Test”添加到xml文件中的所有节点并替换相同的文件。

try
    {
    XMLOutputter  xmlOut = new XMLOutputter();
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File("D://Test//sample.xml");
    Document document = (Document) builder.build(xmlFile);
    Element rootNode = document.getRootElement();
    String Original_data=xmlOut.outputElementContentString(rootNode);
    String Test_Data="",Output_Data;
    List<?> list = rootNode.getChildren();
    PrintStream out = new PrintStream(new FileOutputStream("D://Test/sample.xml"));
    Element node=null;
    for(int i=0;i<list.size();i++)
      {
        node=(Element) list.get(i);
        Test_Data+="<"+node.getName()+"_Test "+__________+"="+node.getAttributeValue(________)+">"; //In ______ Needs to get Only Name of Attribute.

        List<?> n_list=node.getChildren();
        Element node2=null;
        for(int j=0;j<n_list.size();j++)
        {
            node2=(Element) n_list.get(j);

              String Str = new String(xmlOut.outputString(node2));
              Test_Data+=Str.replace(node2.getName(),node2.getName()+"_Test");
        }
        Test_Data+="</"+node.getName()+"_Test>";
      }
    out.println("<"+rootNode.getName()+">"+Original_data+Test_Data+"</"+rootNode.getName()+">");
    }

Sample.xml

 <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<catalog>
 <book id="bk101_Test">
  <author>_Worked</author>
  <title>XML Developer's Guide</title>
  <genre>Computer</genre>
  <price>44.95</price>
  <publish_date>2000-10-01</publish_date>
  <description>An in-depth look at creating applications 
  with XML.</description>    
</book>
  <book id="bk112_Test">
  <author>Galos, Mike</author>
  <title>Visual Studio 7: A Comprehensive Guide</title>
  <genre>Computer</genre>
  <price>49.95</price>
  <publish_date>2001-04-16</publish_date>
  <description>Microsoft Visual Studio 7 is explored in depth,
  looking at how Visual Basic, Visual C++, C#, and ASP+ are 
  integrated into a comprehensive development 
  environment.</description>    
</book>
</catalog>

这解决了我的问题

node.getAttributes().get(0).getName()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM