GVKun编程网logo

使用NodeList遍历XML中的所有元素(nodelist 遍历)

16

本文将带您了解关于使用NodeList遍历XML中的所有元素的新内容,同时我们还将为您解释nodelist遍历的相关知识,另外,我们还将为您提供关于Java学习之Xml系列二:xml按条件查询、xml

本文将带您了解关于使用NodeList遍历XML中的所有元素的新内容,同时我们还将为您解释nodelist 遍历的相关知识,另外,我们还将为您提供关于 Java学习之Xml系列二:xml按条件查询、xml递归遍历所有元素和属性、HTML / Javascript:遍历本地(服务器端)文件夹的所有元素、html-垂直对齐列表中的所有元素、java – 使用nodeList创建XML文档的实用信息。

本文目录一览:

使用NodeList遍历XML中的所有元素(nodelist 遍历)

使用NodeList遍历XML中的所有元素(nodelist 遍历)

我想遍历XML打印中的所有元素。我的问题是,在staff1标记之后,我一直收到空指针异常,即john 465456433 gmail1 area1 city1

这是我的Java代码,用于打印xml文件中的所有元素:

File fXmlFile = new File("file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);

doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

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

System.out.println("----------------------------");

Node n=null;
Element eElement=null;

for (int i = 0; i < nList.getLength(); i++) {           
  System.out.println(nList.getLength());     
  n= nList.item(i);                            
  System.out.println("\nCurrent Element :" + n.getNodeName());


  if (n.getNodeType() == Node.ELEMENT_NODE) {
    eElement = (Element) n.getChildNodes();
    System.out.println("\nCurrent Element :" + n.getNodeName());
    name = eElement.getElementsByTagName("name").item(i).getTextContent(); //here throws null pointer exception after printing staff1 tag
    phone = eElement.getElementsByTagName("phone").item(i).getTextContent();
    email = eElement.getElementsByTagName("email").item(i).getTextContent();
    area = eElement.getElementsByTagName("area").item(i).getTextContent();
    city = eElement.getElementsByTagName("city").item(i).getTextContent();
  }
  n.getNextSibling();
}

XML档案:

<?xml version="1.0"?>
<company>
  <staff1>
    <name>john</name>
    <phone>465456433</phone>
    <email>gmail1</email>
    <area>area1</area>
    <city>city1</city>
  </staff1>
  <staff2>
    <name>mary</name>
    <phone>4655556433</phone>
    <email>gmail2</email>
    <area>area2</area>
    <city>city2</city>
  </staff2>
  <staff3>
    <name>furvi</name>
    <phone>4655433</phone>
    <email>gmail3</email>
    <area>area3</area>
    <city>city3</city>
  </staff3>
</company>

预期产量:

john
465456433
gmail1
area1
city1
mary
4655556433
gmail2
area2
city2
furvi
4655433
gmail3
area3
city3

 Java学习之Xml系列二:xml按条件查询、xml递归遍历所有元素和属性

Java学习之Xml系列二:xml按条件查询、xml递归遍历所有元素和属性

xml中加入了几条,为了方便查询时作为示例。

话不多说见代码注释:

DTD文件:SwordTypeDefinition.dtd

<?xml version="1.0" encoding="UTF-8"?>
<!ELEMENT SwordLibrary (Sword*)>
<!ELEMENT Sword (SwordName,Price,Attack)>
<!ELEMENT SwordName (#PCDATA)>
<!ELEMENT Price (#PCDATA)>
<!ELEMENT Attack (#PCDATA)>
<!ATTLIST Sword sno CDATA #REQUIRED>
<!ATTLIST Price type CDATA #IMPLIED>
<!ATTLIST Attack factor CDATA "1.0">

XML文件:SwordLib.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE SwordLibrary SYSTEM "SwordTypeDefinition.dtd">
<SwordLibrary>
<Sword sno=''s1''>
<SwordName>欢欣之刃</SwordName>
<Price>1000</Price>
<Attack>10</Attack>
</Sword>
<Sword sno=''s2''>
<SwordName>夜叉</SwordName>
<Price>2050</Price>
<Attack factor="2.0">30</Attack>
</Sword>
<Sword sno=''s3''>
<SwordName>魔棒</SwordName>
<Price type="Dollar">200</Price>
<Attack>0</Attack>
</Sword>
</SwordLibrary>

java代码:

package JavaLeaner.XmlTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class XmlDemo2 {

    /*
     * 按照属性sno查询
     */
    @Test
    public void Test1() throws IOException, ParserConfigurationException, SAXException 
    {
        System.out.println("请输入查找的sword的sno:");
        //这里是java 的控制台输入方法,老忘记,TT
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        String sno=br.readLine();
        Element st= FindSwordBySno(sno);
        if (st != null) {
            String sname = st.getElementsByTagName("SwordName").item(0).getTextContent();
            System.out.println("此剑为:" + sname);
        }
        else
        {
            System.out.println("这里不卖!!" );
        }
        
/*        请输入查找的sword的sno:
        s2
        此剑为:夜叉
        */
    }
    
    Element FindSwordBySno(String sno)throws ParserConfigurationException, SAXException, IOException
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docDuilder = factory.newDocumentBuilder();
        Document doc = docDuilder.parse("src/JavaLeaner/XmlTest/SwordLib.xml");
        NodeList list = doc.getElementsByTagName("Sword");
        for(int i=0;i<list.getLength();i++)
        {
            Element swordTag=(Element)list.item(i);
            String snoText=swordTag.getAttribute("sno");
            if(snoText.equals(sno))
            {
                return swordTag;
            }
        }
        return null;
    }
    
    
    /*
     * 递归遍历整个xml文档的元素和属性
     */
    @Test
    public void Test2() throws IOException, ParserConfigurationException, SAXException 
    {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docDuilder = factory.newDocumentBuilder();
        Document doc = docDuilder.parse("src/JavaLeaner/XmlTest/SwordLib.xml");
        //取文档根元素
        Element rootElement= doc.getDocumentElement();
        String rootName = rootElement.getTagName();
        System.out.println(rootName);
        DeepIn(rootElement);
        

    }
    
    void DeepIn(Element parentElement)
    {
        NodeList list=parentElement.getChildNodes();
        for(int i=0;i<list.getLength();i++)
        {
            if (list.item(i) instanceof Element) {
                Element nodeElement = (Element) list.item(i);
                String eName = nodeElement.getNodeName();
                System.out.println(eName);
                NamedNodeMap nnm=nodeElement.getAttributes();
                //注意:NamedNodeMap也不支持java.lang.Iterable,所以不能增强佛如循环
                for(int j=0;j<nnm.getLength();j++)
                {
                    String aName = nnm.item(j).getNodeName();
                    String aText = nnm.item(j).getTextContent();
                    System.out.println("    "+aName+"="+aText);
                }
                DeepIn(nodeElement);
            }
            else
            {
                //System.out.println("not Element:"+list.item(i).getTextContent()+"------");
/*                注意: getChildNodes()获取的不仅仅包括子元素,还包括其他的字符串等文本,这里之所以会出现这些not Element:-----,是因为xml文件中有许多空白符和换行的缘故
 *                 在实际使用中,可以像本例一样用instanceof Element的条件判断将这些东西过滤掉。
 *                 这个结果不包含属性部分的代码:
 *                 SwordLibrary
                not Element:
                ------
                Sword
                not Element:
                ------
                SwordName
                not Element:欢欣之刃------
                not Element:
                ------
                Price
                not Element:1000------
                not Element:
                ------
                Attack
                not Element:10------
                not Element:
                ------
                not Element:
                ------
                Sword
                not Element:
                ------
                SwordName
                not Element:夜叉------
                not Element:
                ------
                Price
                not Element:2050------
                not Element:
                ------
                Attack
                not Element:30------
                not Element:
                ------
                not Element:
                ------
                Sword
                not Element:
                ------
                SwordName
                not Element:魔棒------
                not Element:
                ------
                Price
                not Element:200------
                not Element:
                ------
                Attack
                not Element:0------
                not Element:
                ------
                not Element:
                ------*/

            }
    
        }
/*        结果:
 * 
 *         SwordLibrary
        Sword
            sno=s1
        SwordName
        Price
        Attack
            factor=1.0
        Sword
            sno=s2
        SwordName
        Price
        Attack
            factor=2.0
        Sword
            sno=s3
        SwordName
        Price
            type=Dollar
        Attack
            factor=1.0*/

    }
    
    
    
}


HTML / Javascript:遍历本地(服务器端)文件夹的所有元素

HTML / Javascript:遍历本地(服务器端)文件夹的所有元素

基本上,我有一个非常简单的网站,其根目录如下所示:

/images/
index.html
stuff.js

我想通过某种方式递归遍历/ images /目录中的每个文件,并按照我网站的一部分顺序显示它们.例如,如果/ images /包含:

images/a/a.png
images/b.png
images/c.jpg
....

然后index.html中的某个地方将包含:

<img src="images/a/a.png" />
<img src="images/b.png" />
<img src="images/c.jpg" />
....

我的第一个想法是使用stuff.js中的document.write()函数执行此操作,但我找不到在Javascript中迭代本地文件目录的好方法.我看到了一些关于AJAX的内容,但所有这些示例都涉及编辑现有文件,我显然不想这样做.

我目前的解决方案只是手动创建一个包含/ images /中所有文件的字符串数组,但这样做让我觉得“必须有更好的方法!”

如果我不清楚,请告诉我.

谢谢!

解决方法

也许最好的方法是使用服务器端语言为您执行此操作,并使用异步Javascript请求来显示数据.

此示例使用PHP列出指定目录中的所有文件,使用xmlhttprequest加载此输出并将结果转换为图像标记:

getimages.PHP:

<?PHP

    //The directory (relative to this file) that holds the images
    $dir = "Images";


    //This array will hold all the image addresses
    $result = array();

    //Get all the files in the specified directory
    $files = scandir($dir);


    foreach($files as $file) {

        switch(ltrim(strstr($file,'.'),'.')) {

            //If the file is an image,add it to the array
            case "jpg": case "jpeg":case "png":case "gif":

                $result[] = $dir . "/" . $file;

        }
    }

    //Convert the array into JSON
    $resultJson = json_encode($result);

    //Output the JSON object
    //This is what the AJAX request will see
    echo($resultJson);

?>

index.html(与getimages.PHP相同的目录):

<!DOCTYPE html>
<html>
    <head>
        <title>Image List Thing</title>
    </head>
    <body>

        <div id="images"></div>
        <input type="button" onclick="callForImages()" value="Load" />

        <script>

            //The div element that will contain the images
            var imageContainer = document.getElementById("images");



            //Makes an asynch request,loading the getimages.PHP file
            function callForImages() {

                //Create the request object
                var httpReq = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");

                //When it loads,httpReq.onload = function() {

                    //Convert the result back into JSON
                    var result = JSON.parse(httpReq.responseText);

                    //Show the images
                    loadImages(result);
                }

                //Request the page
                try {
                    httpReq.open("GET","getimages.PHP",true);
                    httpReq.send(null);
                } catch(e) {
                    console.log(e);
                }

            }


            //Generates the images and sticks them in the container
            function loadImages(images) {

                //For each image,for(var i = 0; i < images.length; i++) {

                    //Make a new image element,setting the source to the source in the array
                    var newImage = document.createElement("img");
                    newImage.setAttribute("src",images[i]);

                    //Add it to the container
                    imageContainer.appendChild(newImage);

                }

            }

            </script>

    </body>
</html>

请注意,这只是一个例子.您可能希望确保AJAX调用成功,并且JSON转换在服务器代码和客户端上都有效.

html-垂直对齐列表中的所有元素

html-垂直对齐列表中的所有元素

我有一个使用Ul和Li元素的导航栏.除了垂直因素,我还按自己的方式设计了所有样式.我希望所有元素都垂直居中,但不起作用.我试过使用vertical-align:middle;在元素上,但它什么也没做.

这是我的代码.

nav {
  background-color: #4D0066;
  width: 400px;
  height: 60px;
  border: 3px solid black;
  border-radius: 5px 5px 35px 35px;
  ;
  margin: 5px auto;
}

ul {
  font-size: 0;
  text-align: center;
}

li,li a:after {
  display: inline-block;
  vertical-align: middle;
}
li a:after {
  content:'';
  height: 100%;
}

a {
  color: white;
  text-decoration: none;
  font-size: 15pt;
  display: block;
  padding: 0 10px;
}

.home {
  width: 32px;
  display: block;
  vertical-align: middle;
}
<nav>
  <ul>
    <li><a href="#">Roster</a></li>
    <li><a href="#">News</a></li>
    <li>
      <a href="#"><img src="images/home.png"></a>
    </li>
    <li><a href="#">Arena</a></li>
    <li><a href="#">Leagues</a></li>
  </ul>
</nav>
最佳答案
使ul中的li项对齐.您应该将ul的显示设置为flex,并应用align-items:center或align-items:baseline.居中将使它们垂直居中,基线将使它们彼此对齐.

将高度设置为100%还将确保它占用了提供的整个空间.

有关flexBox的更多信息,请参见:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

nav {
  background-color: #4D0066;
  width: 400px;
  height: 60px;
  border: 3px solid black;
  border-radius: 5px 5px 35px 35px;;
  margin: 5px auto;
}

ul {
  font-size: 0;
  text-align: center;
  display:flex;
  align-items: center;
  height: 100%;
}

li {
  display: inline-block;
}

a {
  color: white;
  text-decoration: none;
  font-size: 15pt;
  display: block;
  padding: 0 10px;
}

.home {
  width: 32px;
  display: block;
  vertical-align: middle;
}
<nav>
  <ul>
    <li><a href="#">Roster</a></li>
    <li><a href="#">News</a></li>
    <li><a href="#"><img src="images/home.png"></a></li>
    <li><a href="#">Arena</a></li>
    <li><a href="#">Leagues</a></li>
  </ul>
</nav>

java – 使用nodeList创建XML文档

java – 使用nodeList创建XML文档

我需要使用NodeList创建一个 XML Document对象.有人可以帮我做这件事.我已经向您展示了下面的代码和xml
import
javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*; import
org.w3c.dom.*;

public class ReadFile {

    public static void main(String[] args) {
        String exp = "/configs/markets";
        String path = "testConfig.xml";
        try {
            Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);
            XPath xPath = XPathFactory.newInstance().newXPath();
            XPathExpression xPathExpression = xPath.compile(exp);
            NodeList nodes = (NodeList)
              xPathExpression.evaluate(xmlDocument,XPathConstants.NODESET);

        } catch (Exception ex) {
            ex.printstacktrace();
        } 
    }
}

xml文件如下所示

<configs>
    <markets>   
        <market>
            <name>Real</name>
        </market>
        <market>
            <name>play</name>
        </market>
    </markets>
</configs>

提前致谢..

解决方法

你应该这样做:

>您创建一个新的org.w3c.dom.Document newXmlDoc,其中存储NodeList中的节点,
>您创建一个新的根元素,并将其附加到newXmlDoc
>然后,对于NodeList中的每个节点n,在newXmlDoc中导入n,然后将n附加为root的子节点

这是代码:

public static void main(String[] args) {
    String exp = "/configs/markets/market";
    String path = "src/a/testConfig.xml";
    try {
        Document xmlDocument = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder().parse(path);

        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression xPathExpression = xPath.compile(exp);
        NodeList nodes = (NodeList) xPathExpression.
                evaluate(xmlDocument,XPathConstants.NODESET);

        Document newXmlDocument = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder().newDocument();
        Element root = newXmlDocument.createElement("root");
        newXmlDocument.appendChild(root);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            Node copyNode = newXmlDocument.importNode(node,true);
            root.appendChild(copyNode);
        }

        printTree(newXmlDocument);
    } catch (Exception ex) {
        ex.printstacktrace();
    }
}

public static void printXmlDocument(Document document) {
    DOMImplementationLS domImplementationLS = 
        (DOMImplementationLS) document.getImplementation();
    LSSerializer lsSerializer = 
        domImplementationLS.createLSSerializer();
    String string = lsSerializer.writetoString(document);
    System.out.println(string);
}

输出是:

<?xml version="1.0" encoding="UTF-16"?>
<root><market>
            <name>Real</name>
        </market><market>
            <name>play</name>
        </market></root>

一些说明:

>我已经将exp改为/ configs / markets / market,因为我怀疑你想要复制市场元素,而不是单一的市场元素
>对于printXmlDocument,我在这个answer中使用了有趣的代码

我希望这有帮助.

如果您不想创建新的根元素,那么您可以使用原始的XPath表达式,它返回一个由单个节点组成的NodeList(请记住,您的XML必须只有一个根元素),您可以直接添加到您的新XML文档.

请参阅以下代码,其中我评论了上面代码中的行:

public static void main(String[] args) {
    //String exp = "/configs/markets/market/";
    String exp = "/configs/markets";
    String path = "src/a/testConfig.xml";
    try {
        Document xmlDocument = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder().parse(path);

        XPath xPath = XPathFactory.newInstance().newXPath();
        XPathExpression xPathExpression = xPath.compile(exp);
        NodeList nodes = (NodeList) xPathExpression.
        evaluate(xmlDocument,XPathConstants.NODESET);

        Document newXmlDocument = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder().newDocument();
        //Element root = newXmlDocument.createElement("root");
        //newXmlDocument.appendChild(root);
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            Node copyNode = newXmlDocument.importNode(node,true);
            newXmlDocument.appendChild(copyNode);
            //root.appendChild(copyNode);
        }

        printXmlDocument(newXmlDocument);
    } catch (Exception ex) {
        ex.printstacktrace();
    }
}

这将为您提供以下输出:

<?xml version="1.0" encoding="UTF-16"?>
<markets>   
        <market>
            <name>Real</name>
        </market>
        <market>
            <name>play</name>
        </market>
    </markets>

今天关于使用NodeList遍历XML中的所有元素nodelist 遍历的讲解已经结束,谢谢您的阅读,如果想了解更多关于 Java学习之Xml系列二:xml按条件查询、xml递归遍历所有元素和属性、HTML / Javascript:遍历本地(服务器端)文件夹的所有元素、html-垂直对齐列表中的所有元素、java – 使用nodeList创建XML文档的相关知识,请在本站搜索。

本文标签: