我正在寻找一种完全通用的方法来使用Java1.8的org.w3c.dom.attr从xml属性中获取值?
以下是我尝试的:
import org.w3c.dom.Attr;
String getAttributeValue(Attr attr) {
if (attr.getSpecified()) {
String value = attr.getValue();
}
else {
throw new RuntimeException("I don't know how to get an attribute value when."
+ "it is not specified with the attribute because my "
+ "implementation does not consider default values in "
+ "the schema.");
}
}
根据javadoc for org.w3c.dom.attr,我的解决方案是不完整的,因为我没有涉及在xml文档的模式中给定默认值的情况。如何完成算法,覆盖所有可能存在正确解决方案的情况,并在解决方案不可能时引发异常?
我的attr示例来自一系列以 javax.imageio.ImageIO.getImageReaders(ImageInputStream stream)
. 它是这样的:
void processImage(final ImageInputStream stream) throws IOException {
Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
while (readers.hasNext()) {
ImageReader reader = readers.next();
reader.setInput(imageInputStream, true);
IIOMetadata metadata = reader.getImageMetadata(0);
String[] names = metadata.getMetadataFormatNames();
int length = names.length;
for (int i = 0; i < length; ++i) {
Node node = metadata.getAsTree(names[i]);
short type = node.getNodeType();
if(type == Node.ATTRIBUTE_NODE) {
System.out.print(name[i])
System.out.print(" = ");
String attributeValue = getAttributeValue(node);
System.out.println(attributeValue);
}
}
}
}
暂无答案!
目前还没有任何答案,快来回答吧!