2014-10-17 59 views
0

我想读取使用Java程序的XML文件数据。但是o/p只显示null。阅读java中的XML数据

想法是从下面的xml文件1.e中读取例如内容名称的值。 Content Value =“AssetFlow_Trial_07.mpg”来自下面的xml文件。但我得到的只是空白输出。

下面是我的XML文件,

XML文件:

<?xml version="1.0" encoding="UTF-8"?> 
<ADI> 
<Metadata> 
<AMS Asset_Name="mntario8616_8889pk_026" Provider="Rogers" Product="DRAOD" Version_Major="4" Version_Minor="12" Description="Kids_in_Hall_Ep__1Package_Asset" Creation_Date="2010-06-11" Provider_ID="HBOworld" Asset_ID="TJPK0000000000000026" Asset_Class="package"/> 
<App_Data App="MOD" Name="Provider_Content_Tier" Value="IFCC_FREE_10"/> 
<App_Data App="MOD" Name="Metadata_Spec_Version" Value="CableLabsVOD1.1"/> 
</Metadata> 
<Asset> 
<Metadata> 

<AMS Asset_Name="mntario8616_8889m_024" Provider="Rogers" Product="DRAOD" Version_Major="1" Version_Minor="0" Description="Kids_in_Hall_Ep__1Title_Movie" Creation_Date="2010-06-11" Provider_ID="HBOworld" Asset_ID="TJMV0000000000000024" Asset_Class="movie"/> 
<App_Data App="MOD" Name="Type" Value="movie"/> 
<App_Data App="MOD" Name="Encryption" Value="N"/> 
<App_Data App="MOD" Name="Audio_Type" Value="Stereo"/> 
<App_Data App="MOD" Name="Languages" Value="en"/> 
<App_Data App="MOD" Name="Viewing_Can_Be_Resumed" Value="Y"/> 
<App_Data App="MOD" Name="HDContent" Value="Y"/> 
</Metadata> 
<Content Value="AssetFlow_Trial_07.mpg"/> 
</Asset> 

这是我的Java代码,

Java代码:

XMLInputFactory factory = null; 
XMLStreamReader reader = null; 

XMLInputFactory factory = null; 
    XMLStreamReader reader = null; 

    try { 
     factory = XMLInputFactory.newInstance(); 
     factory.setProperty(XMLInputFactory.IS_COALESCING, true); 
     reader = factory.createXMLStreamReader(new FileInputStream(new File(
       "D:\\seachange\\AssetFlow Test Files\\DR-Sun3.xml"))); 
     boolean readCharacters = false; 
     while (reader.hasNext()) { 
      int event = reader.next(); 
      switch (event) { 
       case (XMLStreamConstants.START_ELEMENT): { 
        if (reader.getLocalName().equals("Metadata")) { 
         readCharacters = true; 
        } 
        break; 
       } 
       case (XMLStreamConstants.CHARACTERS): { 
        if (readCharacters) { 
         System.out.println(reader.getText()); 
         readCharacters = false; 
        } 
        break; 
       } 
      } 
     } 
    } 
    catch (Throwable t) { 
     t.printStackTrace(); 
    } 
    finally { 
     try { 
      reader.close(); 
     } 
     catch (Throwable t) { 
      t.printStackTrace(); 
     } 
    } 

任何帮助表示赞赏1!

+1

时间来学习如何调试:) – m0skit0 2014-10-17 10:28:09

回答

0

终于做出了一个代码,

import java.io.File; 

import javax.print.Doc; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 

import java.io.File; 
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory; 

import org.w3c.dom.Node; 
import org.w3c.dom.NodeList; 

abstract class AbstractClass 
{ 
abstract NodeList getTagName(String tagName); 
} 
class ActualClass extends AbstractClass 
{ 
DocumentBuilderFactory dbFactory; 
DocumentBuilder dBuilder; 
org.w3c.dom.Document doc; 
String[] attribute; 
public void document() 
{ 
try 
{ 
dbFactory = DocumentBuilderFactory.newInstance(); 
dBuilder = dbFactory.newDocumentBuilder(); 
doc = dBuilder.parse(new File("D:\\seachange\\AssetFlow Test Files\\VIDEOTRON_1.xml")); 
doc.getDocumentElement().normalize(); 

} 
catch (Exception e) 
{ 
e.printStackTrace(); 
} 
} 
NodeList getTagName(String tagName) 
{ 
NodeList mainNode = null; 
if (doc != null) 
{ 
mainNode=doc.getElementsByTagName(tagName); 
} 
return mainNode; 
} 
void readAttribute(NodeList mainNode, String attName) 
{ 
if (doc != null) 
{ 
attribute = new String[mainNode.getLength()]; 
if (mainNode != null) { 

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

attribute[i] = node.getAttributes().getNamedItem(attName).getNodeValue(); 
} 

} 
} 
} 
} 
void printOutput(NodeList mainNode, String attValue) 
{ 
for (int i=0; i< mainNode.getLength(); i++) 
{  

if ((attribute[i]).equals(attValue)) 
{ 
System.out.println(attribute[i]); 

} 

} 
} 
} 


public class TestAbstract { 

public static void main(String[] args) { 
ActualClass A1= new ActualClass(); 
A1.document(); 
NodeList N1= A1.getTagName("Content"); 
A1.readAttribute(N1, "Value"); 
A1.printOutput(N1, "Movie_012.mpg"); 
} 

} 
+0

虽然我无法处理其他部分,该通知的情况下,用户的字符串模式不可用。该部分仍需开发 – TestBud 2014-10-27 07:00:59

+0

以上代码满足我的需求 – TestBud 2014-10-27 07:01:43

0

我正在使用spring来读取文件,但重点是一旦你得到的XML文件,你可以查询到它。如果你的项目是maven。只需做到这一点。

POM:

<properties> 
    <java-version>1.8</java-version> 
    <spring.version>4.1.0.RELEASE</spring.version> 
    <junit.version>4.11</junit.version> 
</properties> 

<dependencies> 
    <dependency> 
     <groupId>org.springframework</groupId> 
     <artifactId>spring-context</artifactId> 
     <version>${spring.version}</version> 
    </dependency> 
    <dependency> 
     <groupId>junit</groupId> 
     <artifactId>junit</artifactId> 
     <version>${junit.version}</version> 
     <scope>test</scope> 
    </dependency> 
</dependencies> 

然后只需在您的主要方法调用函数

public static void main(String[] args) throws Exception { 
    readXmlFile(); 
} 

private static void readXmlFile() throws Exception{ 

    Resource resource = new ClassPathResource("myXmlFile.xml"); 
    File xmlFile = resource.getFile(); 

    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); 
    DocumentBuilder builder = builderFactory.newDocumentBuilder(); 
    builder.setErrorHandler(new DomErrorHandler()); 
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(xmlFile)); 
    Document xmlDocument = builder.parse(in); 
    xmlDocument.getDocumentElement().normalize(); 

    XPathFactory factory = XPathFactory.newInstance(); 
    XPath xPath = factory.newXPath(); 

    String selectFirstNode = "/ADI/Asset/Content[@Value='AssetFlow_Trial_07.mpg']"; 
    Object result = executeXpathExpression(xmlDocument, selectFirstNode, xPath, XPathConstants.NODE); 
    Node firstNode = (Node) result;  
    String nodeName = firstNode.getNodeName(); 
    System.out.println(nodeName); 

} 

public static Object executeXpathExpression(Document xmlDocument, String expression, XPath xPath, QName returnType) { 

    Object result = null; 
    try { 
     XPathExpression xPathExpression = xPath.compile(expression); 
     result = xPathExpression.evaluate(xmlDocument, returnType); 

    } catch (XPathExpressionException e) { 
     e.printStackTrace(); 
    } 
    return result; 
} //end of executeXpathExpression() 
0

首先,你缺少ADI在你的XML文件的末尾结束标记。您可以阅读内容标签的属性“值”。

 File file = new File("test.xml"); 
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
     DocumentBuilder db; 
     try { 
      db = dbf.newDocumentBuilder(); 
     Document doc = db.parse(file); 
     doc.getDocumentElement().normalize(); 

     NodeList l = doc.getElementsByTagName("Content"); 

     for (int j = 0; j < l.getLength(); ++j) { 
      Node prop = l.item(j); 

      NamedNodeMap attr = prop.getAttributes(); 
      if (null != attr) { 
       Node p = attr.getNamedItem("Value"); 
       System.out.println(p.getNodeValue()); 
      } 
     } 
     } catch (ParserConfigurationException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (SAXException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
-1

我想提出一个替代的解决方案,需要使用XMLBeam更少的代码(披露:我与该项目附属)有维护更少的代码是很重要的,当任务变得更加复杂。

public class XMLDemo { 
    public interface Projection { 
    @XBRead("/ADI/Content/@Value") 
    String getContentValue(); 
    } 

    public static main(String[] args) { 
    Projection projection = new XBProjector().io().file("D:\\seachange\\AssetFlow Test Files\\DR-Sun3.xml").read(Projection.class); 
    System.out.println(projection.getContentValue()); 
    } 
}