Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java获取节点的标记名_Java_Xml - Fatal编程技术网

Java获取节点的标记名

Java获取节点的标记名,java,xml,Java,Xml,我需要读取一个小xml文件,并根据一个硬编码的HashMap验证其内容,其中key=tag和value=text位于标记内。 我无法获取节点的标记名。 如果将节点转换为元素,则会出现强制转换异常 我正在使用末日课程阅读: DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();

我需要读取一个小xml文件,并根据一个硬编码的HashMap验证其内容,其中key=tag和value=text位于标记内。 我无法获取节点的标记名。 如果将节点转换为元素,则会出现强制转换异常

我正在使用末日课程阅读:

DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);

        NodeList list = doc.getElementsByTagName("MergeOptions");
        if (list.getLength() == 0)
        {
        //throw
        }
        NodeList config = list.item(0).getChildNodes();
        for (int i = 0; i <= config.getLength() - 1; i++)
        {

            Node setting = config.item(i);
            String nodeName = setting.getNodeValue();
            String value = setting.getTextContent();
            if (defaultMergeOptions.containsKey(nodeName) == false)
            {
                    //throw
            }

            if (defaultMergeOptions.get(nodeName).equals(value))
            {
                    //throw
            }
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
Document doc=dBuilder.parse(xmlFile);
NodeList list=doc.getElementsByTagName(“合并选项”);
if(list.getLength()==0)
{
//扔
}
NodeList config=list.item(0.getChildNodes();

对于(inti=0;i我已经尝试运行您的代码,它工作正常,没有类强制转换异常。 请注意我是如何在for循环中使用元素来获取可能的子元素的名称、值或存在性的

final String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
            "<MergeOptions>\n<sometagName>false</sometagName>\n</MergeOptions>";

final InputStream xsmlStream = new ByteArrayInputStream(xml.getBytes());

final DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
final DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
final Document doc = dBuilder.parse(xsmlStream);

final NodeList nodes = doc.getElementsByTagName("MergeOptions");

for (int i = 0; i < nodes.getLength(); i++) {
    final Element element = (Element) nodes.item(i);
    System.out.println(element.hasChildNodes());
    System.out.println(element.getNodeValue());
    System.out.println(element.getTagName());
}
final String xml=“\n”+
“\n同样\n”;
final InputStream xsmlStream=new ByteArrayInputStream(xml.getBytes());
final DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
最终DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
最终文档doc=dBuilder.parse(xsmlStream);
最终节点列表节点=doc.getElementsByTagName(“合并选项”);
对于(int i=0;i

使用哈希映射将节点名称用作键有点棘手,因为如果XML文件中有多个名称相同、值不同的节点名称,哈希映射将只存储一个唯一的键,因此只验证其中一个相同名称的节点。其他名称相同但值不同的节点将无效。

我正在帮助您解决此问题以下代码结构。一旦看到标记名和值,就可以应用逻辑从HashMap键或值进行比较

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

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

public class Test1 {
    public static void main(String[] args) throws Exception {
        String xmlFile = "test.xml";
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        Element root = doc.getDocumentElement();
        System.out.println(root.getNodeName());

        NodeList list = root.getChildNodes();

        for (int i = 0; i < list.getLength(); i++) {
            Node node = list.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE)
             {
                System.out.println(node.getNodeName() + " : " + node.getTextContent());
             }
        }

    }
}
import javax.xml.parsers.DocumentBuilder;
导入javax.xml.parsers.DocumentBuilderFactory;
导入org.w3c.dom.Document;
导入org.w3c.dom.Element;
导入org.w3c.dom.Node;
导入org.w3c.dom.NodeList;
公共类Test1{
公共静态void main(字符串[]args)引发异常{
字符串xmlFile=“test.xml”;
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
Document doc=dBuilder.parse(xmlFile);
元素根=doc.getDocumentElement();
System.out.println(root.getNodeName());
NodeList list=root.getChildNodes();
对于(int i=0;i
我做了一些不同的事情

似乎有效:

IntegrationTest.getInstance().getLogger().log(Level.INFO, "Reading merge-que file: " + xmlFile.getAbsolutePath());
    try
    {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);

        for (Entry<String, String> entry : defaultMergeOptions.entrySet())
        {
            String tagName = entry.getKey();

            NodeList list = doc.getElementsByTagName(tagName);
            if (list.getLength() != 1)
            {
                IntegrationTest.getInstance().getLogger().log(Level.SEVERE, TestResult.FAIL, "Merge option [{0}] has invalid content. Tag [{1}] missing or to many",
                        new Object[] { xmlFile.getName(), tagName });
                result = TestResult.FAIL;
                continue;
            }

            if (!defaultMergeOptions.get(tagName).equals(list.item(0).getTextContent()))
            {
                IntegrationTest.getInstance().getLogger().log(Level.WARNING, TestResult.FAIL, "Merge option [{0}] has diffrent content for tag [{1}].",
                        new Object[] { xmlFile.getCanonicalPath(), tagName });
                result = TestResult.FAIL;
            }

        }



    }
    catch (Exception e)
    {
        IntegrationTest.getInstance().getLogger().log(Level.SEVERE, SBUtil.stackTraceToString(e.getStackTrace()));
        throw new IntegrationTestException(e);

    }
}
IntegrationTest.getInstance().getLogger().log(Level.INFO,“读取合并que文件:”+xmlFile.getAbsolutePath());
尝试
{
DocumentBuilderFactory dbFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder=dbFactory.newDocumentBuilder();
Document doc=dBuilder.parse(xmlFile);
for(条目:defaultMergeOptions.entrySet())
{
字符串标记名=entry.getKey();
节点列表=doc.getElementsByTagName(标记名);
if(list.getLength()!=1)
{
IntegrationTest.getInstance().getLogger().log(Level.SEVERE,TestResult.FAIL,“合并选项[{0}]的内容无效。缺少标记[{1}]或标记太多”,
新对象[]{xmlFile.getName(),标记名});
结果=TestResult.FAIL;
继续;
}
如果(!defaultMergeOptions.get(tagName).equals(list.item(0).getTextContent()))
{
IntegrationTest.getInstance().getLogger().log(Level.WARNING,TestResult.FAIL,“合并选项[{0}]对标记[{1}]有不同的内容。”,
新对象[]{xmlFile.getCanonicalPath(),标记名});
结果=TestResult.FAIL;
}
}
}
捕获(例外e)
{
IntegrationTest.getInstance().getLogger().log(Level.SEVERE,SBUtil.stackTraceToString(e.getStackTrace());
抛出新的IntegrationTestException(e);
}
}

什么是
defaultMergeOptions
?哈希映射a根据验证xml。它将xml应具有的所有标记作为键,并将xml标记的所有正确值作为值。在代码中添加哈希映射并编辑代码段。
IntegrationTest.getInstance().getLogger().log(Level.INFO, "Reading merge-que file: " + xmlFile.getAbsolutePath());
    try
    {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);

        for (Entry<String, String> entry : defaultMergeOptions.entrySet())
        {
            String tagName = entry.getKey();

            NodeList list = doc.getElementsByTagName(tagName);
            if (list.getLength() != 1)
            {
                IntegrationTest.getInstance().getLogger().log(Level.SEVERE, TestResult.FAIL, "Merge option [{0}] has invalid content. Tag [{1}] missing or to many",
                        new Object[] { xmlFile.getName(), tagName });
                result = TestResult.FAIL;
                continue;
            }

            if (!defaultMergeOptions.get(tagName).equals(list.item(0).getTextContent()))
            {
                IntegrationTest.getInstance().getLogger().log(Level.WARNING, TestResult.FAIL, "Merge option [{0}] has diffrent content for tag [{1}].",
                        new Object[] { xmlFile.getCanonicalPath(), tagName });
                result = TestResult.FAIL;
            }

        }



    }
    catch (Exception e)
    {
        IntegrationTest.getInstance().getLogger().log(Level.SEVERE, SBUtil.stackTraceToString(e.getStackTrace()));
        throw new IntegrationTestException(e);

    }
}