在java中读取xml数据

时间:2014-10-17 10:16:44

标签: java xml

我正在尝试使用java程序读取xml文件数据。但是o / p只显示为null。

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

下面是我的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!

4 个答案:

答案 0 :(得分: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>

然后只需在main方法中调用函数

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()

答案 1 :(得分:0)

首先,您在XML文件末尾缺少ADI结束标记。您可以阅读属性&#39; Value&#39;内容标签。

        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();
        }

答案 2 :(得分: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");
}

}

答案 3 :(得分:-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());
    } 
}