Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/363.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 向HTML标记添加属性_Java_Groovy - Fatal编程技术网

Java 向HTML标记添加属性

Java 向HTML标记添加属性,java,groovy,Java,Groovy,如何转换html输入字符串,该字符串来自: String标签=” 到 ” 有没有什么可能的Java或Groovy方法可以做到这一点 例如: String convert(String input) { //input: <input type=\"submit\" class=\"cssSubmit\"/> //process the input string //processedString: <input type=\"submit\" class=\"cssSub

如何转换html输入字符串,该字符串来自:

String标签=”

有没有什么可能的Java或Groovy方法可以做到这一点

例如:

String convert(String input) {
 //input: <input type=\"submit\" class=\"cssSubmit\"/>
 //process the input string
 //processedString: <input type=\"submit\" class=\"cssSubmit disable\" disabled=\"disabled\"/>
 return processedString;
}
字符串转换(字符串输入){
//输入:
//处理输入字符串
//processedString:
返回处理过的字符串;
}

这是我能想到的最通用的方法:

public static String editTagXML(String tag,
        Map<String, String> newAttributes,
        Collection<String> removeAttributes)
        throws SAXException, IOException,
        ParserConfigurationException, TransformerConfigurationException,
        TransformerException {
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .parse(new InputSource(new StringReader(tag)));
    Element root = doc.getDocumentElement();
    NamedNodeMap attrs = root.getAttributes();
    for (String removeAttr : removeAttributes) {
        attrs.removeNamedItem(removeAttr);
    }
    for (Map.Entry<String, String> addAttr : newAttributes.entrySet()) {
        final Attr attr = doc.createAttribute(addAttr.getKey());
        attr.setValue(addAttr.getValue());
        attrs.setNamedItem(attr);
    }
    StringWriter result = new StringWriter();
    final Transformer transformer = TransformerFactory.newInstance()
            .newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(new DOMSource(doc), new StreamResult(result));
    return result.toString();
}

public static void main(String[] args) throws Exception {
    long start = System.nanoTime();
    String tag = "<input type=\"submit\" class=\"cssSubmit\"/>";
    String edited = editTagXML(tag, new HashMap<String, String>() {{
        put("class", "cssSubmit disable");
        put("disabled", "disabled");
    }}, new ArrayList<>());
    long time = System.nanoTime() - start;
    System.out.println(edited);
    System.out.println("Time: " + time + " ns");
    start = System.nanoTime();
    tag = "<input type=\"submit\" class=\"cssSubmit\"/>";
    editTagXML(tag, new HashMap<String, String>() {{
        put("class", "cssSubmit disable");
        put("disabled", "disabled");
    }}, new ArrayList<>());
    time = System.nanoTime() - start;
    System.out.println("Time2: " + time + " ns");
}
输出:

<input type="submit" class="cssSubmit disable" disabled="disabled"/>
Time3: 1422672 ns
请注意,通常对XML/(X)HTML使用正则表达式非常容易出错。以下是可能破坏上述代码的示例输入的非详尽列表:

  • -由于报价前的空格,此选项将中断
  • -这将中断,因为我们的代码不需要单引号
  • -这将中断,因为
    =
    周围有空格
  • -这将中断,因为在另一个属性的值中存在类似属性的文本

这些情况中的每一个都可以通过某种方式修改模式来修复(虽然我不确定最后一个),但是当模式崩溃时,您可以找到另一个情况。因此,这种技术最好用于由程序生成的输入,而不是由人工编写的输入,即使这样,您也应该小心该程序的输入来自何处(它可能很容易包含上一个示例中的属性值)。

您可以在groovy中执行此操作:

String tag = "<input type=\"submit\" class=\"cssSubmit\"/>"

tag = new XmlSlurper().parseText(tag).with { x ->
    x.@class = 'cssSubmit disable'
    x.@disabled = 'disabled'
    new groovy.xml.StreamingMarkupBuilder().bind { delegate.out << x}.toString()
}​
String tag=“”
tag=new XmlSlurper().parseText(tag).with{x->
x、 @class='cssSubmit disable'
x、 @disabled='disabled'

新的groovy.xml.StreamingMarkupBuilder().bind{delegate.out请不要。到目前为止您尝试了什么?您可以使用XML库或特定于HTML的库,如jsoup。需要更多上下文。它是在字符串中还是在什么中?如果是,字符串包含什么-整个文档还是只包含这一个标记?是否有任何理由不使用DOM对象而不是字符串?事实上,这个问题太广泛了。@Sugan您的问题并不意味着需要进行任何处理。请尝试改写您的问题?我认为可以安全地假设OP希望能够编辑或添加(以及可能删除)从一个包含标签的字符串中得到的属性。这是一个非常有趣的问题,因为使用这样一个简单字符串的XML库可能是多余的,但是更简单的解决方案可能会容易出错,除非输入上有一些限制。我尊重您的时间,看起来解决方案太复杂了,我考虑了几个。其他因素,如性能、新库的使用等。因此,我将重新思考解决此问题的另一种方法。感谢您的支持time@Suganthan,您首先应该做的是了解您的实际任务。“将属性添加到HTML标记”和“将禁用的属性添加到如下所示的标记”之间有很大的区别。在后一种情况下,它可以像
标记一样简单。replaceFirst(“cssSubmit\”,“cssSubmit disable\”disabled=“disabled\”)
。您使用的是
jsoup
库类吗?不,只是标准的Java库。好的,我知道了,后一个看起来更简单、更短
<input type="submit" class="cssSubmit disable" disabled="disabled"/>
Time3: 1422672 ns
private static final Pattern classAttributePattern
        = Pattern.compile("\\bclass=\"([^\"]+)\"");
public static String disableTag(String tag) {
    Matcher matcher = classAttributePattern.matcher(tag);
    if (!matcher.find()) {
        throw new IllegalArgumentException("Doesn't match: " + tag);
    }
    int start = matcher.start();
    int end = matcher.end();
    String classValue = matcher.group(1);
    if (classValue.endsWith(" disable")) {
        return tag; // already disabled
    } else {
        // assume that if the class doesn't end with " disable",
        // then the disabled attribute is not present as well
        return tag.substring(0, start)
                + "class=\"" + classValue
                + " disable\" disabled=\"disabled\""
                + tag.substring(end);
    }
}
String tag = "<input type=\"submit\" class=\"cssSubmit\"/>"

tag = new XmlSlurper().parseText(tag).with { x ->
    x.@class = 'cssSubmit disable'
    x.@disabled = 'disabled'
    new groovy.xml.StreamingMarkupBuilder().bind { delegate.out << x}.toString()
}​