Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.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 在XML文件中的特定位置插入字符串_Java_Xml_Parsing_Dom_Sax - Fatal编程技术网

Java 在XML文件中的特定位置插入字符串

Java 在XML文件中的特定位置插入字符串,java,xml,parsing,dom,sax,Java,Xml,Parsing,Dom,Sax,我有一个XML文件(client_23.XML),如下所示。我有一个字符串变量out,我需要在下面的XML中插入一个特殊的点。这不是我的完整XML,因为我有很多其他嵌套的东西,函数标记将在其中,并且它不一致,因为这个XML是通过代码生成的,所以我需要 <?xml version="1.0"?> <clients> <!-- some other code here --> <function> </function&

我有一个XML文件
(client_23.XML)
,如下所示。我有一个字符串变量
out
,我需要在下面的XML中插入一个特殊的点。这不是我的完整XML,因为我有很多其他嵌套的东西,函数标记将在其中,并且它不一致,因为这个XML是通过代码生成的,所以我需要

<?xml version="1.0"?>
<clients>
    <!-- some other code here -->

    <function>
    </function>

    <function>
    </function>

    <function>
        <name>data_values</name>
        <variables>
            <variable>
            <name>temp</name>
            <type>double</type>
            </variable>
        </variables>
        <block>
            <opster>temp = 1</opster>   
        </block>
    </function>
</clients>
下面是我得到的代码,但我无法理解如何在块标记中输出
data\u value
函数中的变量

StringBuilder out = new StringBuilder();
// some data in out variable, properly formatted with new lines.

String location = key.getPathName();
String clientIdPath = location + "/" + "client_23.xml";
File fileName = new File(clientIdPath);

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
Document document = documentBuilder.parse(fileName);

NodeList dataValueFunction = document.getElementsByTagName("function");
// I have started iterating but I am not able to understand how to insert "out"
// variable inside block
for (int i = 0; i < dataValueFunction.getLength(); i++) {
    Node node = dataValueFunction.item(i);
    System.out.println(node.getNodeName());
    NodeList childList = node.getChildNodes();
    for (int j = 0; j < childList.getLength(); j++) {
        Node node1 = childList.item(j);
        if (node1 != null && node1.getNodeName().equalsIgnoreCase("name")
                        && node1.getTextContent().equalsIgnoreCase("data_values")) {
            // now what should I do here?
        }
    }
}
StringBuilder out=new StringBuilder();
//一些数据输入输出变量,使用新行正确格式化。
字符串位置=key.getPathName();
字符串clientipath=location+“/”+“client_23.xml”;
文件名=新文件(clientdpath);
DocumentBuilderFactory DocumentBuilderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder DocumentBuilder=documentBuilderFactory.newDocumentBuilder();
Document Document=documentBuilder.parse(文件名);
NodeList dataValueFunction=document.getElementsByTagName(“函数”);
//我已经开始迭代,但我无法理解如何插入“out”
//块内变量
对于(int i=0;i
检查这个问题。您可以使用XPath表达式定位正确的函数标记,并使用XPath更新它

这是一个快速代码

public static void main(String[] args) {
    try {
        FileInputStream file = new FileInputStream(new File("data.xml"));
        List<String> outs = Arrays.asList(new String[] { "hello = world", "abc = def" });
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();

        DocumentBuilder builder = builderFactory.newDocumentBuilder();

        Document xmlDocument = builder.parse(file);

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

        System.out.println("*************************");
        String expression = "//clients/function/name[text()='data_values']";
        System.out.println(expression);
        Node nameTag = (Node) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODE);

        for (int i = 0; i < nameTag.getParentNode().getChildNodes().getLength(); i++) {
            if (nameTag.getParentNode().getChildNodes().item(i).getNodeName().equals("block")) {
                System.out.println("GOT BLOCK");
                nameTag.getParentNode().removeChild(nameTag.getParentNode().getChildNodes().item(i));
                Node node = xmlDocument.createElement("block");



                nameTag.getParentNode().appendChild(node);
                for (String out : outs) {
                    Node newNode = xmlDocument.createElement("opster");
                    newNode.setTextContent(out);

                    node.appendChild(newNode);
                }

            }
        }
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        DOMSource source = new DOMSource(xmlDocument);
        StreamResult result = new StreamResult(System.out);
        transformer.transform(source, result);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (XPathExpressionException e) {
        e.printStackTrace();
    } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
publicstaticvoidmain(字符串[]args){
试一试{
FileInputStream文件=新的FileInputStream(新文件(“data.xml”);
List out=Arrays.asList(新字符串[]{“hello=world”,“abc=def”});
DocumentBuilderFactory builderFactory=DocumentBuilderFactory.newInstance();
DocumentBuilder=builderFactory.newDocumentBuilder();
Document xmlDocument=builder.parse(文件);
XPath=XPathFactory.newInstance().newXPath();
System.out.println(“****************************”);
字符串表达式=“//客户机/函数/名称[text()='data_values']”;
System.out.println(表达式);
Node nameTag=(Node)xPath.compile(expression).evaluate(xmlDocument,XPathConstants.Node);
对于(int i=0;i
已编辑:将“out”的值添加到以前存在的“block”元素中

正如@user489732所建议的,使用XPath对节点进行本地化,然后使用您的值创建一个新节点,然后将其插入函数元素。不过,我会使用不同的方法:

public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException, TransformerException {

    // Your initial input
    String myXML = "<?xml version=\"1.0\"?>\n" +
            "<clients>\n" +
            "    <!-- some other code here -->\n" +
            "\n" +
            "    <function>\n" +
            "    </function>\n" +
            "\n" +
            "    <function>\n" +
            "    </function>\n" +
            "\n" +
            "    <function>\n" +
            "        <name>data_values</name>\n" +
            "        <variables>\n" +
            "            <variable>\n" +
            "            <name>temp</name>\n" +
            "            <type>double</type>\n" +
            "            </variable>\n" +
            "        </variables>\n" +
            "        <block>\n" +
            "            <!-- new stuff added and old things were gone -->\n" +
            "            <opster>hello = world</opster>\n" +
            "            <opster>abc = def</opster>\n" +
            "        </block>\n" +
            "    </function>\n" +
            "</clients>";

    // you will have to create an input stream from your XML file,
    // in this case I'm using a ByteArrayInputStream, you'll probably
    // need a FileInputStream
    InputStream myXMLStream = new ByteArrayInputStream(myXML.getBytes(Charset.forName("UTF-8")));

    String out = "My value whatever it is";

    // Create xpath expression
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("/clients/function/block[../name/text() = 'data_values']");

    // Load document
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(myXMLStream);

    // Search for the node
    NodeList blockList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
    Element blockElement = (Element)blockList.item(0);

    // Insert your value inside element "block"
    // CAVEAT: if the value of "out" contains "tags" (xml elements)
    // then "createTextNode" won't work, you need to create elements
    // with the different methods of "document" (document.createXXXX())
    Node textNode = document.createTextNode(out);
    blockElement.insertBefore(textNode, blockElement.getFirstChild());

    // Write the document to its final destination
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(document);

    // instead of System.out, use a more appropriate stream:
     StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);
}
publicstaticvoidmain(String[]args)抛出ParserConfigurationException、IOException、SAXException、XPathExpressionException、TransformerException{
//您的初始输入
字符串myXML=“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“数据\u值\n”+
“\n”+
“\n”+
“临时\n”+
“双重\n”+
“\n”+
“\n”+
“\n”+
“\n”+
“hello=world\n”+
“abc=def\n”+
“\n”+
“\n”+
"";
//您必须从XML文件创建输入流,
//在本例中,我使用的是ByteArrayInputStream,您可能会
//需要一个FileInputStream吗
InputStream myXMLStream=newbytearrayinputstream(myXML.getBytes(Charset.forName(“UTF-8”));
String out=“我的价值,无论它是什么”;
//创建xpath表达式
XPathFactory XPathFactory=XPathFactory.newInstance();
XPath=xPathfactory.newXPath();
XPathExpression expr=xpath.compile(“/clients/function/block[
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException, TransformerException {

    // Your initial input
    String myXML = "<?xml version=\"1.0\"?>\n" +
            "<clients>\n" +
            "    <!-- some other code here -->\n" +
            "\n" +
            "    <function>\n" +
            "    </function>\n" +
            "\n" +
            "    <function>\n" +
            "    </function>\n" +
            "\n" +
            "    <function>\n" +
            "        <name>data_values</name>\n" +
            "        <variables>\n" +
            "            <variable>\n" +
            "            <name>temp</name>\n" +
            "            <type>double</type>\n" +
            "            </variable>\n" +
            "        </variables>\n" +
            "        <block>\n" +
            "            <!-- new stuff added and old things were gone -->\n" +
            "            <opster>hello = world</opster>\n" +
            "            <opster>abc = def</opster>\n" +
            "        </block>\n" +
            "    </function>\n" +
            "</clients>";

    // you will have to create an input stream from your XML file,
    // in this case I'm using a ByteArrayInputStream, you'll probably
    // need a FileInputStream
    InputStream myXMLStream = new ByteArrayInputStream(myXML.getBytes(Charset.forName("UTF-8")));

    String out = "My value whatever it is";

    // Create xpath expression
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("/clients/function/block[../name/text() = 'data_values']");

    // Load document
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document document = documentBuilder.parse(myXMLStream);

    // Search for the node
    NodeList blockList = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
    Element blockElement = (Element)blockList.item(0);

    // Insert your value inside element "block"
    // CAVEAT: if the value of "out" contains "tags" (xml elements)
    // then "createTextNode" won't work, you need to create elements
    // with the different methods of "document" (document.createXXXX())
    Node textNode = document.createTextNode(out);
    blockElement.insertBefore(textNode, blockElement.getFirstChild());

    // Write the document to its final destination
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(document);

    // instead of System.out, use a more appropriate stream:
     StreamResult result = new StreamResult(System.out);

    transformer.transform(source, result);
}
import com.ximpleware.*;

public class replaceContent {
    public static void main(String[] s) throws VTDException, Exception{
        VTDGen vg = new VTDGen();
        AutoPilot ap = new AutoPilot();
        XMLModifier xm = new XMLModifier();
        if (vg.parseFile("d:\\xml\\input2.xml", true)){
            VTDNav vn = vg.getNav();
            ap.bind(vn);
            xm.bind(vn);
            ap.selectXPath("/clients/function/block");
            int i=-1;
            byte[] s1 = ("\r\n\t\t<opster>hello = world</opster>\r\n\t\t"+
                        "<opster>abc = def</opster>\r\n\t").getBytes();
            while((i=ap.evalXPath())!=-1){
                xm.insertAfterHead(s1);
                long l= vn.getContentFragment(); // add new stuff after the starting tag
                xm.removeContent((int)l, (int)(l>>32)); // remove old stuff
            }
            xm.output("d:\\xml\\new.xml");
        }
        }
}