在XmlDocument中插入/替换XML标记

时间:2008-08-19 08:46:08

标签: java xml xquery

我在java中有XmlDocument,使用Weblogic XmlDocument解析器创建。

我想用我自己的数据替换此XMLDocument中标记的内容,或者如果标记不存在则插入标记。

<customdata>
   <tag1 />
   <tag2>mfkdslmlfkm</tag2>
   <location />
   <tag3 />
</customdata>

我想在位置标记中插入一些URL:

<location>http://something</location>

但是否则按原样保留XML。

目前我使用XMLCursor

    XmlObject xmlobj = XmlObject.Factory.parse(a.getCustomData(), options);
    XmlCursor xmlcur = xmlobj.newCursor();

    while (xmlcur.hasNextToken()) {
      boolean found = false;
      if (xmlcur.isStart() && "schema-location".equals(xmlcur.getName().toString())) {
        xmlcur.setTextValue("http://replaced");
        System.out.println("replaced");
        found = true;
      } else if (xmlcur.isStart() && "customdata".equals(xmlcur.getName().toString())) {
        xmlcur.push();
      } else if (xmlcur.isEnddoc()) {
        if (!found) {
          xmlcur.pop();
          xmlcur.toEndToken();
          xmlcur.insertElementWithText("schema-location", "http://inserted");
          System.out.println("inserted");
        }

      }
      xmlcur.toNextToken();
    }

我试图找到一种“快速”xquery方式来执行此操作,因为XmlDocument有一个execQuery方法,但是发现它并不容易。

有人有比这更好的方法吗?看起来有点复杂。

4 个答案:

答案 0 :(得分:4)

基于XPath的方法怎么样?我喜欢这种方法,因为逻辑非常容易理解。代码几乎是自我记录的。

如果您的xml文档可以作为org.w3c.dom.Document对象使用(大多数解析器返回),那么您可以执行以下操作:

// get the list of customdata nodes
NodeList customDataNodeSet = findNodes(document, "//customdata" );

for (int i=0 ; i < customDataNodeSet.getLength() ; i++) {
  Node customDataNode = customDataNodeSet.item( i );

  // get the location nodes (if any) within this one customdata node
  NodeList locationNodeSet = findNodes(customDataNode, "location" );

  if (locationNodeSet.getLength() > 0) {
    // replace
    locationNodeSet.item( 0 ).setTextContent( "http://stackoverflow.com/" );
  }
  else {
    // insert
    Element newLocationNode = document.createElement( "location" );
    newLocationNode.setTextContent("http://stackoverflow.com/" );
    customDataNode.appendChild( newLocationNode );
  }
}

这是执行XPath搜索的辅助方法findNodes。

private NodeList findNodes( Object obj, String xPathString )
  throws XPathExpressionException {

  XPath xPath = XPathFactory.newInstance().newXPath();
  XPathExpression expression = xPath.compile( xPathString );
  return (NodeList) expression.evaluate( obj, XPathConstants.NODESET );
}

答案 1 :(得分:1)

面向对象的方法怎么样?您可以将XML反序列化为对象,在对象上设置位置值,然后序列化回XML。

XStream让这很容易。

例如,您将定义主对象,在您的情况下是CustomData(我使用公共字段来保持示例简单):

public class CustomData {
  public String tag1;
  public String tag2;
  public String location;
  public String tag3;
}

然后初始化XStream:

XStream xstream = new XStream();
// if you need to output the main tag in lowercase, use the following line
xstream.alias("customdata", CustomData.class);  

现在,您可以从XML构造对象,在对象上设置位置字段并重新生成XML:

CustomData d = (CustomData)xstream.fromXML(xml);
d.location = "http://stackoverflow.com";
xml = xstream.toXML(d);

听起来怎么样?

答案 2 :(得分:1)

如果你不知道架构,那么XStream解决方案可能就不可能了。至少XStream现在在你的雷达上,将来可能会派上用场!

答案 3 :(得分:0)

您应该可以使用query

执行此操作

尝试

 fn:replace(string,pattern,replace)

我自己是xquery的新手,我发现它是一种痛苦的查询语言,但是一旦你克服了最初的学习曲线,它确实很安静。

我仍然希望有一种更方便的方式吗?

相关问题