【发布时间】:2021-01-06 02:56:19
【问题描述】:
目标是检查特定属性,如果未找到,则将其附加到现有属性列表中。
虽然可能有其他可用选项,但此示例仅限于使用 HTMLDocument 对象和相关对象。
import java.io.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
class AddAttributeTest
{
static String srg = "<html> " +
" <head>" +
" Hello World" +
" </head>" +
" <body a1=\"ABC\" a2=\"3974\" a3=\"A1B2\"> " +
" <H1>Start Here<H1>" +
" <p>This is the body</p>" +
" </body>" +
"</html>" ;
public static void main(String[] args)
{
EditorKit kit = new HTMLEditorKit();
HTMLDocument doc = new HTMLDocument();//
try
{
Reader rd = new StringReader(srg);
kit.read(rd, doc, 0);
ElementIterator it = new ElementIterator(doc);
Element elem = null;
while ( (elem = it.next()) != null )
{
if (elem.getName().equals("body"))
{
AttributeSet as = elem.getAttributes();
if (as.isDefined("a1"))
{
System.out.println("a1 exists : " + as.getAttribute("a1"));
}
if (as.isDefined("a4"))
{
System.out.println("a4 exists : " + as.getAttribute("a4"));
}
else
{
System.out.println("a4 is missing and need to add");
//Add the missing attribute to the end of the existing list of attributes.
//elem - only get....() calls exist.
//as - only get...() calls and checks exist.
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.exit(1);
}
}
这个例子说明它能够找到“a1”属性并打印出它的值。
a1 exists : ABC
a4 is missing and need to add
接下来它会尝试找到它没有找到的“a4”属性并尝试添加它。
使用 Eclipse,我检查了 Element 和 AttributeSet 对象的可用调用,它们都是 getters() 或布尔检查。没有任何“添加”例程或 setters() 可调用。
搜索和任何对添加属性的引用都以各种不同的方式实现,除了我尝试的方式。
是否可以使用 HTMLDocument 和相关调用来实现它?
【问题讨论】:
标签: java html dom attributes