下面列出了org.w3c.dom.Document#getElementsByTagName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @param xmlConfiguration InputStream that carries xml configuration
* @return returns a InputStream that has evaluated system variables in input
* @throws CarbonException
*/
public static InputStream replaceSystemVariablesInXml(InputStream xmlConfiguration) throws CarbonException {
DocumentBuilderFactory documentBuilderFactory = getSecuredDocumentBuilder();
DocumentBuilder documentBuilder;
Document doc;
try {
documentBuilder = documentBuilderFactory.newDocumentBuilder();
documentBuilder.setEntityResolver(new CarbonEntityResolver());
doc = documentBuilder.parse(xmlConfiguration);
} catch (Exception e) {
throw new CarbonException("Error in building Document", e);
}
NodeList nodeList = null;
if (doc != null) {
nodeList = doc.getElementsByTagName("*");
}
if (nodeList != null) {
for (int i = 0; i < nodeList.getLength(); i++) {
resolveLeafNodeValue(nodeList.item(i));
}
}
return toInputStream(doc);
}
/**
* Returns the dataframe size from a document. Returns -1 if no size element is found
* @param doc input doc
* @return size of the respective dataframe
* @throws DataFrameException thrown if the size value can not be parsed
*/
private static int getSize(Document doc) throws DataFrameException{
NodeList sizeElements = doc.getElementsByTagName("dataFrame");
int size = -1;
if (sizeElements.getLength() == 1) {
Node sizeNode = sizeElements.item(0);
if (sizeNode.getNodeType() == Node.ELEMENT_NODE) {
Element sizeElement = (Element) sizeNode;
String sizeStr = sizeElement.getAttribute("size");
if(sizeStr != null && !"".equals(sizeStr)){
try {
size = Integer.parseInt(sizeStr);
}
catch (Exception e){
throw new DataFrameException(String.format("error parsing size attribute '%s'",sizeStr));
}
}
}
}
return size;
}
private static List<WikiPageDetail> readXml(InputStream fis) throws IOException, SAXException, ParserConfigurationException, ParseException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fis);
List<WikiPageDetail> result = new ArrayList<>();
NodeList nodeList = doc.getElementsByTagName("com.taskadapter.redmineapi.bean.WikiPageDetail");
for(int i=0;i<nodeList.getLength();i++) {
Node pageNode = nodeList.item(i);
WikiPageDetail wikiPageDetail = new WikiPageDetail();
for(int j=0;j<pageNode.getChildNodes().getLength();j++) {
Node paramNode = pageNode.getChildNodes().item(j);
if("#text".equals(paramNode.getNodeName())) {
continue;
}
setPageParam(paramNode, wikiPageDetail);
}
result.add(wikiPageDetail);
}
return result;
}
@Test
public void testPathParseXMLDocument()
{
String path = "path/to/xml/files";
List<String> pathElements = Arrays.asList(path.split("/"));
FileInfo folder = FileFolderServiceImpl.makeFolders(fileFolderService, companyHome, pathElements, ContentModel.TYPE_FOLDER);
FileInfo file = createXmlFile(folder.getNodeRef());
try
{
Document doc = xsltFunctions.parseXMLDocument(companyHome, path + "/" + file.getName());
NodeList foodNodes = doc.getElementsByTagName("food");
assertEquals(10, foodNodes.getLength());
}
catch (Exception ex)
{
log.error("Error!", ex);
fail(ex.getMessage());
}
}
@Test
public void testSingleNodesXML() throws JSONException, Exception {
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("node")
.path("info/").accept(MediaType.APPLICATION_XML)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
String xml = response.getEntity(String.class);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document dom = db.parse(is);
NodeList nodes = dom.getElementsByTagName("nodeInfo");
assertEquals("incorrect number of elements", 1, nodes.getLength());
verifyNodesXML(nodes);
}
/**
* Extract environment variables.
*
* @param document the document
* @param envvarElement the environment variable element
* @return the list
*/
private List<EnvVar> extractEnvironmentVariables(Document document, String elementName) {
List<EnvVar> list = new ArrayList<>();
NodeList nodeList = document.getElementsByTagName(elementName);
for (int index = 0; index < nodeList.getLength(); index++) {
Element element = (Element) nodeList.item(index);
Class<?> type = null;
try {
type = Class.forName(element.getAttribute(ENVVAR_TYPE_ATTRIBUTE));
} catch (ClassNotFoundException e) {
ConsoleManager.getInstance().exception(this, e);
}
// Assume not predefined, will get sorted out later
EnvVar envVar = new EnvVar(element.getAttribute(ENVVAR_NAME_ATTRIBUTE), type, false);
if (element.hasAttribute(ENVVAR_VALUE_ATTRIBUTE)) {
envVar.setValue(element.getAttribute(ENVVAR_VALUE_ATTRIBUTE));
}
list.add(envVar);
}
return list;
}
@Test
public void testJobIdXML() throws Exception {
WebResource r = resource();
Map<JobId, Job> jobsMap = appContext.getAllJobs();
for (JobId id : jobsMap.keySet()) {
String jobId = MRApps.toString(id);
ClientResponse response = r.path("ws").path("v1").path("mapreduce")
.path("jobs").path(jobId).accept(MediaType.APPLICATION_XML)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
String xml = response.getEntity(String.class);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document dom = db.parse(is);
NodeList job = dom.getElementsByTagName("job");
verifyAMJobXML(job, appContext);
}
}
@Test
public void testAppsXMLMulti() throws JSONException, Exception {
rm.start();
MockNM amNodeManager = rm.registerNode("127.0.0.1:1234", 2048);
rm.submitApp(CONTAINER_MB, "testwordcount", "user1");
rm.submitApp(2048, "testwordcount2", "user1");
amNodeManager.nodeHeartbeat(true);
WebResource r = resource();
ClientResponse response = r.path("ws").path("v1").path("cluster")
.path("apps").accept(MediaType.APPLICATION_XML)
.get(ClientResponse.class);
assertEquals(MediaType.APPLICATION_XML_TYPE, response.getType());
String xml = response.getEntity(String.class);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
Document dom = db.parse(is);
NodeList nodesApps = dom.getElementsByTagName("apps");
assertEquals("incorrect number of elements", 1, nodesApps.getLength());
NodeList nodes = dom.getElementsByTagName("app");
assertEquals("incorrect number of elements", 2, nodes.getLength());
rm.stop();
}
/**
* This method parses the OperationResult (SES response) to get the RessourceID
*
* @param result
* @return {@link String}
* @throws Exception
*/
public synchronized static String getSubscriptionIDfromSES(OperationResult result) throws Exception{
String tag = "muse-wsa:ResourceId";
//build meta document
DocumentBuilderFactory docFac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFac.newDocumentBuilder();
Document doc = docBuilder.parse(result.getIncomingResultAsStream());
NodeList list = doc.getElementsByTagName(tag);
if (list.getLength() != 0) {
Node node = list.item(0);
return node.getTextContent();
}
return null;
}
public static NodeList getXMLNodes(final String xmlFileName, final String tagName) {
NodeList nList = null;
try {
File xmlFile = new File(xmlFileName);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);
doc.getDocumentElement().normalize();
nList = doc.getElementsByTagName(tagName);
} catch (Exception e) {
e.printStackTrace();
}
return nList;
}
private void SendFile(HttpServletRequest Req, HttpServletResponse response) throws Exception
{
String Param=Req.getParameter(DriverRemote.PARAM);
if (PDLog.isDebug())
PDLog.Debug("SendFile Param:"+Param);
DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLObjects = DB.parse(new ByteArrayInputStream(Param.getBytes("UTF-8")));
NodeList OPDObjectList = XMLObjects.getElementsByTagName("Id");
Node OPDObject = OPDObjectList.item(0);
String Id=OPDObject.getTextContent();
OPDObjectList = XMLObjects.getElementsByTagName("Ver");
OPDObject = OPDObjectList.item(0);
String Ver=OPDObject.getTextContent();
DB.reset();
PDDocs doc=new PDDocs(SParent.getSessOPD(Req));
doc.setPDId(Id);
if (Ver!=null && Ver.length()!=0)
doc.LoadVersion(Id, Ver);
else
doc.LoadCurrent(Id);
ServletOutputStream out=response.getOutputStream();
PDMimeType mt=new PDMimeType(SParent.getSessOPD(Req));
mt.Load(doc.getMimeType());
response.setContentType(mt.getMimeCode());
response.setHeader("Content-disposition", "inline; filename=" + doc.getName());
try {
if (Ver!=null && Ver.length()!=0)
doc.getStreamVer(out);
else
doc.getStream(out);
} catch (Exception e)
{
out.close();
throw e;
}
out.close();
}
@Test
public void run() throws TransformerException, ClassNotFoundException, InstantiationException,
IllegalAccessException, ClassCastException
{
// print input
printSnippet("Stylesheet:", getXsl());
printSnippet("Source before transformation:", getSourceXml());
// transform to DOM result
Transformer t = getTransformer();
DOMResult result = new DOMResult();
t.transform(getStreamSource(), result);
// print output
printSnippet("Result after transformation:", prettyPrintDOMResult(result));
// do some assertions
Document document = (Document)result.getNode();
NodeList nodes = document.getElementsByTagName("valeur2");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
AssertJUnit.assertEquals("Node value mismatch",
"Valeur " + (i + 1),
node.getFirstChild().getNodeValue());
AssertJUnit.assertEquals("Node attribute mismatch",
"Attribut " + (i + 1),
node.getAttributes().item(0).getNodeValue());
}
}
@Test
public void testGetNamedItemNS() throws Exception {
Document document = createDOMWithNS("NamedNodeMap03.xml");
NodeList nodeList = document.getElementsByTagName("body");
nodeList = nodeList.item(0).getChildNodes();
Node n = nodeList.item(7);
NamedNodeMap namedNodeMap = n.getAttributes();
Node node = namedNodeMap.getNamedItemNS("urn:BooksAreUs.org:BookInfo", "aaa");
assertEquals(node.getNodeValue(), "value");
}
public static void addHandset(String file,String name,Hashtable<String,String> attri) throws Exception{
DocumentBuilderFactory domfac=DocumentBuilderFactory.newInstance();
DocumentBuilder dombuilder=domfac.newDocumentBuilder();
FileInputStream is=new FileInputStream(file);
Document doc=dombuilder.parse(is);
NodeList nodeList = doc.getElementsByTagName("devices");
if(nodeList != null && nodeList.getLength()>=1){
Node deviceNode = nodeList.item(0);
Element device = doc.createElement("device");
device.setTextContent(name);
for(Iterator itrName=attri.keySet().iterator();itrName.hasNext();){
String attriKey = (String)itrName.next();
String attriValue = (String)attri.get(attriKey);
device.setAttribute(attriKey, attriValue);
}
deviceNode.appendChild(device);
}
//save
TransformerFactory tf=TransformerFactory.newInstance();
Transformer t=tf.newTransformer();
Properties props=t.getOutputProperties();
props.setProperty(OutputKeys.ENCODING, "GB2312");
t.setOutputProperties(props);
DOMSource dom=new DOMSource(doc);
StreamResult sr=new StreamResult(file);
t.transform(dom, sr);
}
public static void useMultiThread(File platformHome)
{
Path p = platformHome.toPath();
Path serverxml = p.resolve(TOMCAT_SERVER_XML_PATH).toAbsolutePath();
final File serverFile = serverxml.toFile();
if (serverFile.exists())
{
try
{
boolean isDirty = false;
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbFactory.newDocumentBuilder();
Document doc = db.parse(serverFile);
NodeList nodes = doc.getElementsByTagName(FIND_TAG_NODE);
for (int i = 0; i < nodes.getLength(); i++) {
Node n = nodes.item(i);
NamedNodeMap attrs = n.getAttributes();
Node ss = attrs.getNamedItem(SS_ATTRIBUTE);
if (ss != null) {
ss.setTextContent(SS_RESET_VALUE);
isDirty = true;
}
}
if (isDirty) {
// save change
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(serverFile);
transformer.transform(source, result);
}
}
catch (Exception e)
{
throw new IllegalStateException(String.format("Failed to access the server.xml file at: %s", serverFile), e);
}
}
else
{
throw new IllegalStateException(String.format("%s doesn't exist.", serverFile));
}
}
/**
* Imports ANY kind of OpenProdoc object(s) (doc, folder, definition, object of any kind,..) in XML format from a file
* @param XMLFile local file containing the object
* @param ParentFolderId Folder Id for importing folders or docs.
* @return Number of objects found and processed in the XML
* @throws PDException In any error
*/
public int ProcessXML(File XMLFile, String ParentFolderId) throws PDException
{
if (PDLog.isInfo())
PDLog.Info("DriverGeneric.ProcessXML>:XMLFile="+XMLFile.getAbsolutePath()+" ParentFolderId="+ParentFolderId);
try {
DocumentBuilder DB = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document XMLObjects = DB.parse(XMLFile);
NodeList OPDObjectList = XMLObjects.getElementsByTagName(ObjPD.XML_OPDObject);
Node OPDObject = null;
ObjPD Obj2Build=null;
int Tot=0;
if (PDLog.isDebug())
PDLog.Debug("DriverGeneric.ProcessXML:Elements="+OPDObjectList.getLength());
for (int i=0; i<OPDObjectList.getLength(); i++)
{
OPDObject = OPDObjectList.item(i);
Obj2Build=BuildObj(OPDObject);
if (Obj2Build instanceof PDDocs)
{
((PDDocs)Obj2Build).ImportXMLNode(OPDObject, XMLFile.getAbsolutePath().substring(0,
XMLFile.getAbsolutePath().lastIndexOf(File.separatorChar)),
ParentFolderId, true);
Tot++;
}
else if (Obj2Build instanceof PDFolders)
; // ((PDFolders)Obj2Build).ImportXMLNode(OPDObject, ParentFolderId, false);
else
{
Obj2Build.ProcesXMLNode(OPDObject);
Tot++;
}
}
DB.reset();
if (PDLog.isInfo())
PDLog.Info("DriverGeneric.ProcessXML<");
return(Tot);
}catch(Exception ex)
{
PDLog.Error(ex.getLocalizedMessage());
throw new PDException(ex.getLocalizedMessage());
}
}
private void implNbinstHost(TestHandler handler) throws ParserConfigurationException, IOException, IllegalArgumentException, SAXException {
FileObject libs = FileUtil.getConfigFile("org-netbeans-api-project-libraries/Libraries");
if (libs != null) {
final List<FileObject> schemas = new ArrayList<FileObject>(3);
schemas.add(null);
final FileObject schema2 = FileUtil.getConfigFile("ProjectXMLCatalog/library-declaration/2.xsd");
if (schema2 != null) {
schemas.add(schema2);
}
final FileObject schema3 = FileUtil.getConfigFile("ProjectXMLCatalog/library-declaration/3.xsd");
if (schema3 != null) {
schemas.add(schema3);
}
next: for (FileObject lib : libs.getChildren()) {
SAXException lastException = null;
for (FileObject schema : schemas) {
lastException = null;
try {
final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setValidating(true);
if (schema != null) {
docBuilderFactory.setNamespaceAware(true);
docBuilderFactory.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaLanguage", //NOI18N
"http://www.w3.org/2001/XMLSchema"); //NOI18N
docBuilderFactory.setAttribute(
"http://java.sun.com/xml/jaxp/properties/schemaSource", //NOI18N
schema.toURI().toString());
}
final DocumentBuilder builder = docBuilderFactory.newDocumentBuilder();
builder.setErrorHandler(XMLUtil.defaultErrorHandler());
builder.setEntityResolver(EntityCatalog.getDefault());
Document doc = builder.parse(new InputSource(lib.toURL().toString()));
NodeList nl = doc.getElementsByTagName("resource");
for (int i = 0; i < nl.getLength(); i++) {
Element resource = (Element) nl.item(i);
validateNbinstURL(new URL(XMLUtil.findText(resource)), handler, lib);
}
continue next;
} catch (SAXException e) {
lastException = e;
}
}
throw lastException;
}
}
for (FileObject f : NbCollections.iterable(FileUtil.getConfigRoot().getChildren(true))) {
for (String attr : NbCollections.iterable(f.getAttributes())) {
if (attr.equals("instanceCreate")) {
continue; // e.g. on Services/Hidden/org-netbeans-lib-jakarta_oro-antlibrary.instance prints stack trace
}
Object val = f.getAttribute(attr);
if (val instanceof URL) {
validateNbinstURL((URL) val, handler, f);
}
}
}
assertNoErrors("No improper nbinst URLs", handler.errors());
}
/**
*
* @param user. The owner of the rule
* @param rule
* @param medium. The selected communication ways. (e.g SMS, E-Mail, ...)
* @param sensor. Sensor ID
* @return meta for BR5: Sensor failure
* @throws Exception
*/
public static synchronized String createTextFailureMeta(User user, BasicRule rule, String medium, String sensor) throws Exception {
// final <BAW_Meta> pattern
String finalMeta = "";
// This is the WNS ID of the user. Each user is subscribed to the WNS with an E-Mail address.
String wnsID;
String regelName = rule.getName();
// get the wnsID
if (medium.equals("SMS")) {
wnsID = user.getWnsSmsId();
} else {
wnsID = user.getWnsEmailId();
}
// location of the meta file
URL metaURL = new URL(SesConfig.resLocation_meta_text);
// message with place holders
String message =
"_T_userID="
+ wnsID
+ "_T_shortMessageEinstieg=SM Regel "
+ regelName
+ " hat einen Alarm ausgeloest. "
+ "Fuer den Sensor " + sensor + " kommen keine Daten mehr. Zeitpunkt:_R__T_MessageEinstieg=Regel "
+ regelName
+ " hat einen Alarm ausgeloest. "
+ "Fuer den Sensor " + sensor + " kommen keine Daten mehr. Zeitpunkt:_R_._T_shortMessageAusstieg=SM Regel "
+ regelName
+ " hat den Alarmzustand beendet. "
+ "Fuer den Sensor " + sensor + " kommen wieder Daten. Zeitpunkt:_R__T_MessageAusstieg=Regel "
+ regelName
+ " hat den Alarmzustand beendet. "
+ "Fuer den Sensor " + sensor + " kommen wieder Daten. Zeitpunkt:_R_!_T_";
// build meta document
DocumentBuilderFactory docFac = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFac.newDocumentBuilder();
Document doc = docBuilder.parse(metaURL.openStream());
// transformer for final output
Transformer transormer = TransformerFactory.newInstance().newTransformer();
transormer.setOutputProperty(OutputKeys.INDENT, "yes");
// parse document
NodeList eventNameList = doc.getElementsByTagName(Constants.selectFunction);
Node eventNameNode = eventNameList.item(0);
eventNameNode.getAttributes().getNamedItem(Constants.newEventName).setTextContent("BAW_META_AUSFALL");
// set message
NodeList messageList = doc.getElementsByTagName(Constants.message);
Node messageNode = messageList.item(0);
messageNode.setTextContent(message);
// build final output
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transormer.transform(source, result);
finalMeta = result.getWriter().toString();
finalMeta = finalMeta.substring(38);
return finalMeta;
}
/**
* Given a Document, converts the XML into a Vector of LoggingEvents.
*
* @param document XML document
* @return Vector of LoggingEvents
*/
private void decodeEvents(final Document document, LogDataCollector collector, ParsingContext parsingContext) {
NodeList eventList = document.getElementsByTagName("record");
for (int eventIndex = 0; eventIndex < eventList.getLength(); eventIndex++) {
Node eventNode = eventList.item(eventIndex);
Logger logger = null;
long timeStamp = 0L;
Level level = null;
String threadName = null;
Object message = null;
String className = null;
String methodName = null;
String exceptionStackTrace = null;
// format of date: 2003-05-04T11:04:52
// ignore date or set as a property? using millis in constructor instead
NodeList list = eventNode.getChildNodes();
int listLength = list.getLength();
if (listLength == 0) {
continue;
}
for (int y = 0; y < listLength; y++) {
Node logEventNode = list.item(y);
String tagName = logEventNode.getNodeName();
if (tagName.equalsIgnoreCase("logger")) {
logger = LoggerFactory.getLogger(getCData(list.item(y)));
} else if (tagName.equalsIgnoreCase("millis")) {
timeStamp = Long.parseLong(getCData(list.item(y)));
} else if (tagName.equalsIgnoreCase("level")) {
level = Level.parse(getCData(list.item(y)));
} else if (tagName.equalsIgnoreCase("thread")) {
threadName = getCData(list.item(y));
} else if (tagName.equalsIgnoreCase("message")) {
message = getCData(list.item(y));
} else if (tagName.equalsIgnoreCase("class")) {
className = getCData(list.item(y));
} else if (tagName.equalsIgnoreCase("method")) {
methodName = getCData(list.item(y));
} else if (tagName.equalsIgnoreCase("exception")) {
exceptionStackTrace = getExceptionStackTrace(list.item(y));
}
}
if (message != null && exceptionStackTrace != null) {
message = message + "\n" + exceptionStackTrace;
} else if (exceptionStackTrace != null) {
message = exceptionStackTrace;
}
LogData logData = new LogData();
logData.setLevel(level);
logData.setClazz(className);
logData.setId(parsingContext.getGeneratedIdAndIncrease());
logData.setDate(new Date(timeStamp));
logData.setLoggerName(logger.getName());
logData.setMessage(StringUtils.defaultString(message != null ? message.toString() : ""));
logData.setThread(threadName);
logData.setMethod(methodName);
logData.setLogSource(parsingContext.getLogSource());
collector.add(logData);
}
}
public Report parse(final ReaderFactory readerFactory) throws ParsingException, ParsingCanceledException {
Document doc = readerFactory.readDocument();
NodeList mainNode = doc.getElementsByTagName("FxCopReport");
Element rootElement = (Element) mainNode.item(0);
parseRules(rootElement);
parseNamespaces(rootElement);
parseTargets(rootElement);
return warnings;
}