Переместил
This commit is contained in:
47
xmltools/XMLIO.java
Normal file
47
xmltools/XMLIO.java
Normal file
@ -0,0 +1,47 @@
|
||||
package tools.xml;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.transform.TransformerException;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import java.io.*;
|
||||
|
||||
/**
|
||||
* Created by IntelliJ IDEA.
|
||||
* User: Igor
|
||||
* Date: 18.12.2005
|
||||
* Time: 15:27:36
|
||||
* To change this template use File | Settings | File Templates.
|
||||
*/
|
||||
public class XMLIO
|
||||
{
|
||||
public static Document newDocument() throws ParserConfigurationException
|
||||
{
|
||||
return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
|
||||
}
|
||||
|
||||
public static Document load(InputStream is) throws ParserConfigurationException, IOException, SAXException
|
||||
{
|
||||
return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
|
||||
}
|
||||
|
||||
public static Document load(String filename) throws ParserConfigurationException, IOException, SAXException
|
||||
{
|
||||
return DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(filename));
|
||||
}
|
||||
|
||||
public static void save(String filename, Document document) throws TransformerException, FileNotFoundException
|
||||
{
|
||||
save(new FileOutputStream(filename), document);
|
||||
}
|
||||
|
||||
public static void save(OutputStream out, Document document) throws TransformerException
|
||||
{
|
||||
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(document), new StreamResult(out));
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
package tools;
|
||||
package tools.xml;
|
||||
|
||||
import javax.xml.parsers.ParserConfigurationException;
|
||||
import javax.xml.xpath.XPath;
|
||||
import javax.xml.xpath.XPathExpression;
|
||||
|
||||
@ -9,13 +10,26 @@ import org.w3c.dom.Element;
|
||||
import org.w3c.dom.NamedNodeMap;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
import org.w3c.dom.ls.DOMImplementationLS;
|
||||
import org.w3c.dom.ls.LSSerializer;
|
||||
import org.xml.sax.SAXException;
|
||||
|
||||
import javax.xml.xpath.XPath;
|
||||
import javax.xml.xpath.XPathConstants;
|
||||
import javax.xml.xpath.XPathExpression;
|
||||
import javax.xml.xpath.XPathExpressionException;
|
||||
import javax.xml.xpath.XPathFactory;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
/**
|
||||
* Created by IntelliJ IDEA.
|
||||
* User: Igor
|
||||
* Date: 18.12.2005
|
||||
* Time: 15:26:59
|
||||
* To change this template use File | Settings | File Templates.
|
||||
*/
|
||||
public class XMLTools
|
||||
{
|
||||
/**
|
||||
@ -35,6 +49,173 @@ public class XMLTools
|
||||
return "";
|
||||
}
|
||||
|
||||
public static Document parse(String xmlString) throws IOException, ParserConfigurationException, SAXException
|
||||
{
|
||||
return XMLIO.load(new ByteArrayInputStream(xmlString.getBytes()));
|
||||
}
|
||||
|
||||
public static Document parse(InputStream xmlString) throws IOException, ParserConfigurationException, SAXException
|
||||
{
|
||||
return XMLIO.load(xmlString);
|
||||
}
|
||||
|
||||
/**
|
||||
* Возвращает вложенный элемент "childName" элемента "parent" <br/>
|
||||
* <element><childName/></element>
|
||||
* @param parent
|
||||
* @param childName
|
||||
* @return Дочерный элемент либо <code>null</code>, если элементов с таким именем нет
|
||||
*/
|
||||
public static Element getChild(Element parent, String childName){
|
||||
NodeList nl = parent.getChildNodes();
|
||||
for (int i = 0; i <nl.getLength(); i++) {
|
||||
if (isElement(nl.item(i), childName)){
|
||||
return (Element)nl.item(i);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Проверяет, является ли <code>node</code> элементом (<code>instanceOf {@link Element}</code>)
|
||||
* и имеет ли имя "tagname"
|
||||
* @param node
|
||||
* @param tagname
|
||||
* @return
|
||||
*/
|
||||
public static boolean isElement(Node node, String tagname){
|
||||
return node instanceof Element && node.getNodeName().equals(tagname);
|
||||
}
|
||||
|
||||
/** Найти узел по атрибуту
|
||||
*/
|
||||
public static Node findNodeOnAttribute(Node node, String nodename, String attribute, String val)
|
||||
{
|
||||
if(node==null) return null;
|
||||
NodeList items = node.getChildNodes();
|
||||
for (int i=0;i<items.getLength();i++)
|
||||
{
|
||||
Node n=items.item(i);
|
||||
if(n.getNodeName().equals(nodename))
|
||||
{
|
||||
NamedNodeMap nnm=n.getAttributes();
|
||||
if(nnm.getNamedItem(attribute).getNodeValue().equals(val)) return n;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
//вернуть первый попавшийся узел среди дочерних
|
||||
public static Node getFirstNodeOnName(Node node,String nodename)
|
||||
{
|
||||
Node[] mas=new Node[50]; //depth
|
||||
int pos=0;
|
||||
mas[pos] = node.getFirstChild();
|
||||
while (mas[pos] != null)
|
||||
{
|
||||
if(mas[pos].getNodeName().equals(nodename))
|
||||
{
|
||||
return mas[pos];
|
||||
}
|
||||
if(mas[pos].getFirstChild()!=null)
|
||||
{
|
||||
pos++;
|
||||
mas[pos]=mas[pos-1].getFirstChild();
|
||||
}else
|
||||
{
|
||||
//если не идёт дальше пытаемся подняться в верх по дереву
|
||||
while (true)
|
||||
{
|
||||
mas[pos] = mas[pos].getNextSibling();
|
||||
if (mas[pos]==null)
|
||||
{
|
||||
if(pos>0){ pos--; }else{ break; }
|
||||
}else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return first from childs in first deep level on name
|
||||
* @param node Find in
|
||||
* @param nodename Name node
|
||||
* @return node
|
||||
*/
|
||||
public static Node getNodeOnName(Node node,String nodename)
|
||||
{
|
||||
if(node==null) return null;
|
||||
Node nextNode = node.getFirstChild();
|
||||
while(nextNode != null)
|
||||
{
|
||||
if(nextNode.getNodeName().equals(nodename)) return nextNode;
|
||||
nextNode=nextNode.getNextSibling();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
//Сериализовать узел в строку
|
||||
public static String getOuterXML(Node node)
|
||||
{
|
||||
DOMImplementationLS domImplementation = (DOMImplementationLS) node.getOwnerDocument().getImplementation();
|
||||
LSSerializer lsSerializer = domImplementation.createLSSerializer();
|
||||
if (!(node instanceof Document))
|
||||
{
|
||||
lsSerializer.getDomConfig().setParameter("xml-declaration", false);
|
||||
}
|
||||
return lsSerializer.writeToString(node);
|
||||
}
|
||||
|
||||
/**
|
||||
* Поиск среди текущего и дочерних узлов
|
||||
* @param {Node} node Корневой узел
|
||||
* @param {String} nodename Имя первого попавшегося узла
|
||||
* @returns {undefined}
|
||||
*/
|
||||
public static Node findFirstNode(Node node, String nodename)
|
||||
{
|
||||
Node result=null;
|
||||
if(node==null) return result;
|
||||
javax.xml.xpath.XPathFactory xPathfactory = javax.xml.xpath.XPathFactory.newInstance();
|
||||
XPath xpath = xPathfactory.newXPath();
|
||||
XPathExpression expr=null;
|
||||
Object exprResult=null;
|
||||
try {
|
||||
expr = xpath.compile("//*/"+nodename);
|
||||
exprResult = expr.evaluate(node, XPathConstants.NODESET);
|
||||
} catch (XPathExpressionException ex) {
|
||||
|
||||
}
|
||||
NodeList nodeList = (NodeList) exprResult;
|
||||
if (nodeList.getLength() > 0)
|
||||
result = nodeList.item(0);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Найти узел по имени
|
||||
* @param node
|
||||
* @param nodename
|
||||
* @return
|
||||
*/
|
||||
public static Node findFirstNode_v2(Node node, String nodename)
|
||||
{
|
||||
if(node==null || nodename==null) return null;
|
||||
NodeList items = node.getChildNodes();
|
||||
for (int i=0;i<items.getLength();i++)
|
||||
{
|
||||
Node n=items.item(i);
|
||||
if(n.getNodeName().equals(nodename))
|
||||
{
|
||||
return n;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
/** Найти узел по атрибуту
|
||||
*/
|
||||
public static Node findNodeOnAttribute(Node node, String nodename, String attribute, String val)
|
||||
@ -73,32 +254,6 @@ public class XMLTools
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Поиск среди текущего и дочерних узлов
|
||||
* @param {Node} node Корневой узел
|
||||
* @param {String} nodename Имя первого попавшегося узла
|
||||
* @returns {undefined}
|
||||
*/
|
||||
public static Node findFirstNode(Node node, String nodename)
|
||||
{
|
||||
Node result=null;
|
||||
if(node==null) return result;
|
||||
javax.xml.xpath.XPathFactory xPathfactory = javax.xml.xpath.XPathFactory.newInstance();
|
||||
XPath xpath = xPathfactory.newXPath();
|
||||
XPathExpression expr=null;
|
||||
Object exprResult=null;
|
||||
try {
|
||||
expr = xpath.compile("//*/"+nodename);
|
||||
exprResult = expr.evaluate(node, XPathConstants.NODESET);
|
||||
} catch (XPathExpressionException ex) {
|
||||
|
||||
}
|
||||
NodeList nodeList = (NodeList) exprResult;
|
||||
if (nodeList.getLength() > 0)
|
||||
result = nodeList.item(0);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Присвоить дочерние узлы первого дерева второму если их нет, иначе дополнить либо заменить. (Работает через рекурсию нужно для передачи параметров между окнами)
|
||||
* @param {XML} first Узел где ханятся настройки
|
||||
Reference in New Issue
Block a user