如何在java中修改xml标签的具体值?

发布于 2024-12-07 19:58:51 字数 2485 浏览 0 评论 0原文

我是 xml 的新手。我使用了一个 xml 文件,如下所示:

<?xml version="1.0" encoding="UTF-8" ?> 
      - <root>
      - <key>
           <Question>Is the color of the car</Question> 
           <Ans>black?</Ans> 
       </key>
     - <key>
           <Question>Is the color of the car</Question> 
           <Ans>black?</Ans> 
       </key>
     - <key>
           <Question>Is the news paper</Question> 
           <Ans>wallstreet?</Ans> 
      </key>
    - <key>
          <Question>fragrance odor</Question> 
          <Ans>Lavendor?</Ans> 
     </key>
   - <key>
          <Question>Is the baggage collector available</Question> 
         <Ans /> 
     </key>
  </root>

从上面的 xml 我只想更改

             <Ans>wallstreet?</Ans> as <Ans>WonderWorld</Ans>.

如何更改 wallstreet?作为奇迹世界?通过我的java应用程序。

我编写了如下所示的java方法:

  public void modifyNodeval(){
 try{
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new File(path));
        Node nodes1 = doc.getElementsByTagName("*");
        for(int j=0;j<nodes1.getLength();j++)
        {
            //Get the staff element by tag name directly
            Node nodes = doc.getElementsByTagName("key").item(j);
            //loop the staff child node
            NodeList list = nodes.getChildNodes();

            for (int i = 0; i != list.getLength(); ++i)
            {
                Node child = list.item(i);

               if (child.getNodeName().equals("Ans")) {

                   child.getFirstChild().setNodeValue("WonderWorld") ;
                   System.out.println("tag val modified success fuly");
               }

           }
       }
       TransformerFactory transformerFactory = TransformerFactory.newInstance();
       Transformer transformer = transformerFactory.newTransformer();
       DOMSource source = new DOMSource(doc);
       StreamResult result = new StreamResult(path);
       transformer.transform(source, result);
   }
   catch (Exception e) 
   {
       e.printStackTrace();
   }
}

通过使用上面的代码,我可以将所有标签文本更改为奇迹世界,但我的意图是我只想更改wallstreet?作为奇迹世界。

任何人请帮助我......

i am new to work on xml.i have used an xml file as follows:

<?xml version="1.0" encoding="UTF-8" ?> 
      - <root>
      - <key>
           <Question>Is the color of the car</Question> 
           <Ans>black?</Ans> 
       </key>
     - <key>
           <Question>Is the color of the car</Question> 
           <Ans>black?</Ans> 
       </key>
     - <key>
           <Question>Is the news paper</Question> 
           <Ans>wallstreet?</Ans> 
      </key>
    - <key>
          <Question>fragrance odor</Question> 
          <Ans>Lavendor?</Ans> 
     </key>
   - <key>
          <Question>Is the baggage collector available</Question> 
         <Ans /> 
     </key>
  </root>

from the above xml i would like to change only

             <Ans>wallstreet?</Ans> as <Ans>WonderWorld</Ans>.

how can i change wallstreet? as WonderWorld? through my java application.

i have written java method as shown below:

  public void modifyNodeval(){
 try{
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new File(path));
        Node nodes1 = doc.getElementsByTagName("*");
        for(int j=0;j<nodes1.getLength();j++)
        {
            //Get the staff element by tag name directly
            Node nodes = doc.getElementsByTagName("key").item(j);
            //loop the staff child node
            NodeList list = nodes.getChildNodes();

            for (int i = 0; i != list.getLength(); ++i)
            {
                Node child = list.item(i);

               if (child.getNodeName().equals("Ans")) {

                   child.getFirstChild().setNodeValue("WonderWorld") ;
                   System.out.println("tag val modified success fuly");
               }

           }
       }
       TransformerFactory transformerFactory = TransformerFactory.newInstance();
       Transformer transformer = transformerFactory.newTransformer();
       DOMSource source = new DOMSource(doc);
       StreamResult result = new StreamResult(path);
       transformer.transform(source, result);
   }
   catch (Exception e) 
   {
       e.printStackTrace();
   }
}

by using above code i am able to change the all tag text as wonder world but my intention is i want change only wallstreet? as WonderWorld.

any body please help me.....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夜未央樱花落 2024-12-14 19:58:51

我建议 XPath 使用更少的代码来准确选择您想要编辑的内容:

XPath xpath = XPathFactory.newInstance().newXPath();
Element e = (Element) xpath.evaluate("//Ans[. = 'wallstreet']", document, XPathConstant.NODE);
if (e != null)
  e.setTextContent("Wonderland");

I would recommend XPath to select exactly what you want to edit with a lot less code:

XPath xpath = XPathFactory.newInstance().newXPath();
Element e = (Element) xpath.evaluate("//Ans[. = 'wallstreet']", document, XPathConstant.NODE);
if (e != null)
  e.setTextContent("Wonderland");
甜尕妞 2024-12-14 19:58:51

使用

if (child.getNodeName().equals("Ans") && child.getTextContent().equals("wallstreet?"))

作为 if 条件。

use

if (child.getNodeName().equals("Ans") && child.getTextContent().equals("wallstreet?"))

as your if condition.

电影里的梦 2024-12-14 19:58:51

您没有检查节点的值是否为“wallstreet”? - 所以它只是更改每个第一个子节点。

String str = child.getFirstChild( ).getNodeValue( );
if ( "wallstreet?".compareTo( str ) == 0 )
{
    child.getFirstChild( ).setNodeValue( "WonderWorld" );
    System.out.println( "tag val modified success fuly" );
}

You are not checking if the value of the node is "wallstreet?" - so it simply changes every first child node.

String str = child.getFirstChild( ).getNodeValue( );
if ( "wallstreet?".compareTo( str ) == 0 )
{
    child.getFirstChild( ).setNodeValue( "WonderWorld" );
    System.out.println( "tag val modified success fuly" );
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文