Good day ppl.
I have class:
public class XmlModifier {
private DocumentBuilderFactory docFactory = null;
private DocumentBuilder docBuilder = null;
private Document document = null;
private TransformerFactory transformFactory = null;
private Transformer transform = null;
private DOMSource source = null;
private StreamResult streamRes = null;
private boolean exepDocBuilderAlarm = true;
public XmlModifier() {
this.docFactory = DocumentBuilderFactory.newInstance();
try {
this.docBuilder = docFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
this.exepDocBuilderAlarm = false;
e.printStackTrace();
}
}
public void prepareXMLMessage(File file, String userName, String userPassword, String reqId, Integer NUMBER_OF_MSG_SENDS) {
if (exepDocBuilderAlarm != false) {
try {
document = docBuilder.parse(file);
setElementValues("si:sourceInfo", addElementsToArray("si:reqId,si:reqTag"), addElementsToArray(reqId + "," + reqId), NUMBER_OF_MSG_SENDS);
setElementValues("usr:user", addElementsToArray("usr:id,usr:password"), addElementsToArray(userName + "," + userPassword), NUMBER_OF_MSG_SENDS);
setElementValues("meth:method", addElementsToArray("meth:id,meth:tag"), addElementsToArray(reqId + "," + reqId), NUMBER_OF_MSG_SENDS);
setElementValues("tb:tradeField", addElementsToArray("tb:value"), addElementsToArray(reqId), NUMBER_OF_MSG_SENDS);
this.transformFactory = TransformerFactory.newInstance();
this.transform = transformFactory.newTransformer();
this.source = new DOMSource(document);
this.streamRes = new StreamResult(file);
this.transform.transform(source, streamRes);
System.out.println("Done to execute XmlModifier");
} catch (Exception e) {
e.printStackTrace();
} finally {
this.docFactory = null;
this.docBuilder = null;
this.transformFactory = null;
this.transform = null;
this.source = null;
this.streamRes = null;
}
}
}
private void setElementValues(String rootElement, String[] childElements, String[] childElementsValues, Integer msgIDIncrement) {
Node nodeRootElement = document.getElementsByTagName(rootElement).item(0);
NodeList childElementlist = nodeRootElement.getChildNodes();
for (int i = 0; i < childElements.length; i++) {
for (int z = 0; z < childElementlist.getLength(); z++) {
Node node = childElementlist.item(z);
if (childElements[i].equals(node.getNodeName())) {
node.setTextContent(childElementsValues[i]);
}
}
}
}
private String[] addElementsToArray(String elements) {
String[] theArray = null;
theArray = elements.split(",");
return theArray;
}
}
On input I have xml which is not well formed sometimes. The problem of DOM parser is that in my point of view DOM parser parsing whole xml from the beggining which my have special symbols like < > & " ' is not good for me.
How can I on input to prepareXMLMessage(..) provide xml with < > & " ', then in prepareXMLMessage(..) parse it with no problems(change some values inside elements) and than as output provide xml with < > & " ' back???
Thank you for help.
Related
in my custom processor i need to update config file(it is placed in one of nifi folder, it is not original config ) based on data which i get from upstream connection but i can't get desired result what should i do?
is there any way i can controll upstream connection flowfile
destination i mean when i make debugging i use this function fileQueue.drainTo(file, batchSize) in this part "file " was null
here is one more thing i am interested in, on this line
session.commit() i always get errors that :"trnasfer operation isn't specified" and tanks to it whole operation is failed ?
it seems that when i try to make session.exportTo() operations it doesnt write anything in dotCopyFile, how should i fix it?
should i clean fileQueue and then make session.commit()?
FlowFile flowfile;
#Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
final String conflictResponse = context.getProperty(CONFLICT_RESOLUTION).getValue();
final ArrayList value = new ArrayList<>();
flowfile = session.get();
if (flowfile == null) {
return;
}
value.add(flowfile.getAttribute("filename"));
session.remove(flowfile);
final File directory = new File(context.getProperty(DIRECTORY).evaluateAttributeExpressions().getValue());
final boolean keepingSourceFile = context.getProperty(KEEP_SOURCE_FILE).asBoolean();
final ComponentLog logger = getLogger();
if (fileQueue.size() < 100) {
final long pollingMillis = context.getProperty(POLLING_INTERVAL).asTimePeriod(TimeUnit.MILLISECONDS);
if ((queueLastUpdated.get() < System.currentTimeMillis() - pollingMillis) && listingLock.tryLock()) {
try {
final Set<File> listing = performListing(directory, fileFilterRef.get(), context.getProperty(RECURSE).asBoolean().booleanValue());
queueLock.lock();
try {
listing.removeAll(inProcess);
if (!keepingSourceFile) {
listing.removeAll(recentlyProcessed);
}
fileQueue.clear();
fileQueue.addAll(listing);
queueLastUpdated.set(System.currentTimeMillis());
recentlyProcessed.clear();
if (listing.isEmpty()) {
context.yield();
}
} finally {
queueLock.unlock();
}
} finally {
listingLock.unlock();
}
}
}
final int batchSize = context.getProperty(BATCH_SIZE).asInteger();
final List<File> file = new ArrayList<>(batchSize);
queueLock.lock();
try {
fileQueue.drainTo(file, batchSize);
if (file.isEmpty()) {
return;
} else {
inProcess.addAll(file);
}
} finally {
queueLock.unlock();
}
//make xml parsing
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
try {
dBuilder = dbFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
try {
File f = file.get(0);
doc = dBuilder.parse(f);
} catch (IOException e) {
e.printStackTrace();
} catch (org.xml.sax.SAXException e) {
e.printStackTrace();
}
NodeList nList = doc.getElementsByTagName("localAttributes");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
start = eElement.getElementsByTagName("start").item(0).getTextContent();
startDate = eElement.getElementsByTagName("startDate").item(0).getTextContent();
endDate = eElement.getElementsByTagName("endDate").item(0).getTextContent();
patch = eElement.getElementsByTagName("patch").item(0).getTextContent();
runAs = eElement.getElementsByTagName("runAs").item(0).getTextContent();
makeVersion = eElement.getElementsByTagName("makeVersion").item(0).getTextContent();
///parameter = eElement.getElementsByTagName("parameter").item(0).getTextContent();
}
}
final ListIterator<File> itr = file.listIterator();
FlowFile flowFile1 = null;
try {
final Path directoryPath = directory.toPath();
while (itr.hasNext()) {
final File files = itr.next();
final Path filePath = files.toPath();
final Path relativePath = directoryPath.relativize(filePath.getParent());
String relativePathString = relativePath.toString() + "/";
if (relativePathString.isEmpty()) {
relativePathString = "./";
}
final Path absPath = filePath.toAbsolutePath();
final String absPathString = absPath.getParent().toString() + "/";
flowFile1 = session.create();
final long importStart = System.nanoTime();
flowFile1 = session.importFrom(filePath, keepingSourceFile, flowFile1);
final long importNanos = System.nanoTime() - importStart;
final long importMillis = TimeUnit.MILLISECONDS.convert(importNanos, TimeUnit.NANOSECONDS);
flowFile1 = session.putAttribute(flowFile1, CoreAttributes.FILENAME.key(), files.getName());
flowFile1 = session.putAttribute(flowFile1, CoreAttributes.PATH.key(), relativePathString);
flowFile1 = session.putAttribute(flowFile1, CoreAttributes.ABSOLUTE_PATH.key(), absPathString);
Map<String, String> attributes = getAttributesFromFile(filePath);
if (attributes.size() > 0) {
flowFile1 = session.putAllAttributes(flowFile1, attributes);
}
InputStream ffStream = session.read(flowFile1);
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = builderFactory.newDocumentBuilder();
Document xmlDocument = builder.parse(ffStream);
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression myNodeList = (XPathExpression) xPath.compile("/localAttributes");
Node nodeGettingChanged = (Node) myNodeList.evaluate(xmlDocument, XPathConstants.NODE);
NodeList childNodes = nodeGettingChanged.getChildNodes();
boolean make=false;
for (int i = 0; i != childNodes.getLength(); ++i) {
Node child = childNodes.item(i);
if (!(child instanceof Element))
continue;
if(child.getNodeName().equals("start")){
String date;
for(int j=0;j<value.size();j++) {
if(value.get(j).length()>10){
date=value.get(j).substring(0,10);
}
else{
date=value.get(j);
}
if (date == child.getFirstChild().getTextContent()){
child.getFirstChild().setNodeValue(addOneDay(child.getFirstChild().getTextContent()));
make=true;
}
}
}
if(make){
if(child.getNodeName().equals("runAs")){
child.getFirstChild().setNodeValue("true");
}
}
}
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(xmlDocument);
String path = "C:/Users/user/Desktop/nifi-1.3.0/nifi-assembly/target/nifi-1.3.0-bin/nifi-1.3.0/1/conf.xml";
File f = new File(path);
StreamResult file1 = new StreamResult(f);
try {
transformer.transform(source, file1);
} catch (TransformerException e) {
e.printStackTrace();
}
session.write(flowFile1, new StreamCallback() {
#Override
public void process(InputStream inputStream, OutputStream outputStream) throws IOException {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = transformerFactory.newTransformer();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
}
DOMSource source = new DOMSource(xmlDocument);
ffStream.close();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult result = new StreamResult(bos);
try {
transformer.transform(source, result);
} catch (TransformerException e) {
e.printStackTrace();
}
byte[] array = bos.toByteArray();
outputStream.write(array);
}
});
Path tempDotCopyFile = null;
try {
final Path rootDirPath = Paths.get("C://Users//user//Desktop//try2//nifi-1.3.0//1");
final Path tempCopyFile = rootDirPath.resolve("." + flowFile1.getAttribute(CoreAttributes.FILENAME.key()));
final Path copyFile = rootDirPath.resolve(flowFile1.getAttribute(CoreAttributes.FILENAME.key()));
if (!Files.exists(rootDirPath)) {
if (context.getProperty(CREATE_DIRS).asBoolean()) {
Files.createDirectories(rootDirPath);
} else {
flowFile1 = session.penalize(flowFile1);
session.transfer(flowFile1,REL_FAILURE);
logger.error("Penalizing {} and routing to 'failure' because the output directory {} does not exist and Processor is "
+ "configured not to create missing directories", new Object[]{flowFile1, rootDirPath});
return;
}
}
final Path dotCopyFile = tempCopyFile;
tempDotCopyFile = dotCopyFile;
Path finalCopyFile = copyFile;
final Path finalCopyFileDir = finalCopyFile.getParent();
if (Files.exists(finalCopyFileDir)) { // check if too many files already
final int numFiles = finalCopyFileDir.toFile().list().length;
if (numFiles >= 34) {
flowFile1 = session.penalize(flowFile1);
logger.warn("Penalizing {} and routing to 'failure' because the output directory {} has {} files, which exceeds the "
+ "configured maximum number of files", new Object[]{flowFile1, finalCopyFileDir, numFiles});
session.transfer(flowFile1,REL_FAILURE);
return;
}
}
if (Files.exists(finalCopyFile)) {
switch (conflictResponse) {
case REPLACE_RESOLUTION:
Files.delete(finalCopyFile);
logger.info("Deleted {} as configured in order to replace with the contents of {}", new Object[]{finalCopyFile, flowFile1});
break;
case IGNORE_RESOLUTION:
session.transfer(flowFile1, REL_SUCCESS);
logger.info("Transferring {} to success because file with same name already exists", new Object[]{flowFile1});
return;
case FAIL_RESOLUTION:
flowFile1 = session.penalize(flowFile1);
logger.warn("Penalizing {} and routing to failure as configured because file with the same name already exists", new Object[]{flowFile1});
session.transfer(flowFile1,REL_FAILURE);
return;
default:
break;
}
}
session.exportTo(flowFile1, dotCopyFile, false);
final String permissions = "-rwxrwx---";
if (permissions != null && !permissions.trim().isEmpty()) {
try {
String perms = stringPermissions(permissions);
if (!perms.isEmpty()) {
Files.setPosixFilePermissions(dotCopyFile, PosixFilePermissions.fromString(perms));
}
} catch (Exception e) {
logger.warn("Could not set file permissions to {} because {}", new Object[]{permissions, e});
}
}
boolean renamed = false;
for (int i = 0; i < 10; i++) { // try rename up to 10 times.
if (dotCopyFile.toFile().renameTo(finalCopyFile.toFile())) {
renamed = true;
break;// rename was successful
}
Thread.sleep(100L);// try waiting a few ms to let whatever might cause rename failure to resolve
}
if (!renamed) {
if (Files.exists(dotCopyFile) && dotCopyFile.toFile().delete()) {
logger.debug("Deleted dot copy file {}", new Object[]{dotCopyFile});
}
throw new ProcessException("Could not rename: " + dotCopyFile);
} else {
logger.info("Produced copy of {} at location {}", new Object[]{flowFile1, finalCopyFile});
}
/*session.getProvenanceReporter().send(flowFile, finalCopyFile.toFile().toURI().toString(), stopWatch.getElapsed(TimeUnit.MILLISECONDS));
session.transfer(flowFile, REL_SUCCESS);*/
session.getProvenanceReporter().receive(flowFile1, files.toURI().toString(), importMillis);
//session.transfer(flowFile1, REL_SUCCESS);
session.remove(flowFile1);
} catch (final Throwable t) {
if (tempDotCopyFile != null) {
try {
Files.deleteIfExists(tempDotCopyFile);
} catch (final Exception e) {
logger.error("Unable to remove temporary file {} due to {}", new Object[]{tempDotCopyFile, e});
}
}
flowFile1 = session.penalize(flowFile1);
logger.error("Penalizing {} and transferring to failure due to {}", new Object[]{flowFile1, t});
session.transfer(flowFile1,REL_FAILURE);
}
}
if (!isScheduled()) { // if processor stopped, put the rest of the files back on the queue.
queueLock.lock();
try {
while (itr.hasNext()) {
final File nextFile = itr.next();
fileQueue.add(nextFile);
inProcess.remove(nextFile);
}
} finally {
queueLock.unlock();
}
}
} catch (IOException e1) {
e1.printStackTrace();
} catch (TransformerConfigurationException e1) {
e1.printStackTrace();
} catch (ParserConfigurationException e1) {
e1.printStackTrace();
} catch (XPathExpressionException e1) {
e1.printStackTrace();
} catch (org.xml.sax.SAXException e) {
e.printStackTrace();
}
session.commit();
}
I have an xml document to parse which have nested nodes I have tried in my way but unable to get job done as desired.
XML doc is
<Items>
<Item>
<MediumImage>
<URL>http://ecx.images-amazon.com/images/I/51l7DDD1qNL._SL160_.jpg</URL>
<Height Units="pixels">160</Height>
<Width Units="pixels">160</Width>
</MediumImage>
<Title>Fallout 4 Vault Dweller's Survival Guide Collector's Edition: Prima Official Game Guide</Title>
<OfferSummary>
<LowestNewPrice>
<Amount>1952</Amount>
</OfferSummary>
</Item>
.
.
.
</Items>
I have done to fetch Title node values as
private static NodeList fetchTitle(String requestUrl) {
NodeList nodeList = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(requestUrl);
nodeList = doc.getElementsByTagName("Title");
} catch (Exception e) {
System.out.println("Message is " + e.getCause() + "...." + e.getMessage());
throw new RuntimeException(e);
}
return nodeList;
}
and I print as in main() as
titleList = fetchTitle(requestUrl);
for (int i = 0; i < titleList.getLength(); i++) {
Node node = titleList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
// do something with the current element
System.out.println(node.getNodeName());
System.out.println("Signed Title is \"" + node.getTextContent() + "\"");
System.out.println();
}
}
and Amount value from LowestNewPrice Node as
private static NodeList fetchPrice(String requestUrl) {
NodeList nodeList = null;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(requestUrl);
nodeList = doc.getElementsByTagName("LowestNewPrice");
} catch (Exception e) {
System.out.println("Message is " + e.getCause() + "...." + e.getMessage());
throw new RuntimeException(e);
}
return nodeList;
}
and I print as in main() as
priceList = fetchPrice(requestUrl);
for (int i = 0; i < priceList.getLength(); i++) {
Node node = priceList.item(i).getFirstChild();
if (node.getNodeType() == Node.ELEMENT_NODE) {
// do something with the current element
System.out.println(node.getNodeName());
System.out.println("Signed Price is \"" + node.getTextContent() + "\"");
System.out.println();
}
}
through above code I get all Title values first and then I get Amount values separately, but what I really want is to have a POJO class as
public class Item {
String title;
String price;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
and add values to Item object using setTitle(), setPrice(), and return a List<Item>
any help please.
You might try this solution please.
Parse your data and add to List<Item> as :
public static Document fetchRequiredData(String src) {
Document doc = null;
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser;
try {
parser = dbFactory.newDocumentBuilder();
doc= parser.parse(src);
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return doc;
}
public static List<Item> parseItemInfo(Document doc){
List<Item> items = new ArrayList<Item>();
NodeList itemNodeList = doc.getElementsByTagName("Item");
for (int i = 0; i < itemNodeList.getLength(); i++) {
Node titleNode = doc.getElementsByTagName("Title").item(i);
Node priceNode = doc.getElementsByTagName("LowestNewPrice").item(i).getFirstChild();
if (titleNode.getNodeType() == Node.ELEMENT_NODE || priceNode.getNodeType() == Node.ELEMENT_NODE ) {
Item item = new Item();
item.setDesc(titleNode.getTextContent());
item.setPrice(priceNode.getTextContent());
items.add(item);
}
}
return items;
}
now your List is ready to test in main() method as
public static void main(String[] args) {
List<Item> items = parseItemInfo(fetchRequiredData(requestUrl));
System.out.println("Printing List<Item> contents ...");
for (Item item : items) {
System.out.println("Title is " + item.getTitle());
System.out.println("Price is " + item.getPrice());
System.out.println();
}
}
Hope this one helps.
You can achieve that by using JAXBContext. First create Item class.
#XmlRootElement(name = "Items")
#XmlAccessorType(value = XmlAccessType.FIELD)
public class Items
{
#XmlElement(name = "Item")
private List<Item> item;
public void setItem(List<Item> itemList)
{
this.item = itemList;
}
public List<Item> getItem()
{
return this.item;
}
}
#XmlRootElement(name = "Item")
#XmlAccessorType(vallue = XmlAccessType.FIELD)
public class Item
{
#XmlElement(name = "MediumImage")
private MediumImage image;
#XmlElement(name = "Title")
private String title;
#XmlElement(name = "OfferSummary")
private OfferSummary summary;
getters();
setters();
}
#XmlRootElement(name = "MediumImage")
#XmlAccessorType(value = XmlAccessType.FIELD)
public class MediumImage
{
#XmlElement(name = "URL")
private String url;
....
}
#XmlRootElement(name = "OfferSummary")
#XmlAccessorType(value = XmlAccessType.FIELD)
public class OfferSummary
{
#XmlElement(name = "LowestNewPrice")
private LowestNewPrice lowestPrice;
....
}
Then from the main method use marshaller and unmarshaller method.
public static void main(String[] args)
{
File xmlFile = new File("file path");
JAXBContext context = JAXBContext.newInstance(Items.class);
//To get POJO from xml
Unmarshaller unmarshaller = context.createUnmarshaller();
Items items = (Items) unmarshaller.unmarshal(xmlFile);
}
Currently it seems that you're separating the prices and titles into 2 lists, if you want to store an item's price and title into a single Item object, you can do something like this:
public class Item {
public static void main(String[] args) {
ArrayList<Item> items = new ArrayList<Item>();
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new File("items.xml"));
NodeList itemElements = doc.getElementsByTagName("Item");
for (int i = 0; i < itemElements.getLength(); i++) {
Node itemElement = itemElements.item(i);
NodeList itemChildren = itemElement.getChildNodes();
Item item = new Item();
for (int j = 0; j < itemChildren.getLength(); j++) {
Node n = itemChildren.item(j);
if (n.getNodeName().equalsIgnoreCase("title")) {
item.setTitle(n.getTextContent());
} else if (n.getNodeName().equalsIgnoreCase("OfferSummary")) {
NodeList offerChildren = n.getChildNodes();
for (int k = 0; k < offerChildren.getLength(); k++) {
Node offerChild = offerChildren.item(k);
if (offerChild.getNodeName().equalsIgnoreCase("LowestNewPrice")) {
item.setPrice(offerChild.getTextContent());
}
}
}
}
items.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("items: " + items);
}
String title;
String price;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
#Override
public String toString() {
return "Title: " + title + " Price: " + price;
}
}
What this does is to get all the <Item> elements from the XML and loop through them to get the item's title and price.
It may be a basic question, but I could not manage to find a correct answer. Maybe it is an exceptional usage of SimpleXML.
In SimpleXML (java) I want to read some attributes of an object from XML and then save the Object again to another XML without writing those attributes.
I want to read "Question" object from this XML definition:
<question>
<questionID>0</questionID>
<category>tarih</category>
<difficultyLevel>80</difficultyLevel>
<text>Tarihte gelmiş geçmiş en büyük sınırlara ulaşan imparatorluk, aşağıdakilerden hangisidir?</text>
<alternatives length="4">
<string>Britanya</string>
<string>Roma</string>
<string>Moğol</string>
<string>Osmanlı</string>
</alternatives>
<answerID>0</answerID>
And Serialize it back as follows by eliminating the "alternatives" fields:
<question>
<questionID>0</questionID>
<category>tarih</category>
<difficultyLevel>80</difficultyLevel>
<text>Tarihte gelmiş geçmiş en büyük sınırlara ulaşan imparatorluk, aşağıdakilerden hangisidir?</text>
<answerID>0</answerID>
</question>
Is this possible?
Edit: The java class definition of "Question":
public class Question {
public final static int N_POSSIBLE_ANSWERS=4;
public final static String[] ALTERNATIVE_CAPTIONS = {"A","B","C","D"};
// Attributes
#Element
public int questionID;
#Element
public String category;
#Element
public int difficultyLevel;
#Element
public String text;
#ElementArray
private String[] alternatives;
#Element(required=false)
private int answerID = -1;
// State variables
private int nAddedAlternatives=0;
public String[] getAlternatives() {
return alternatives;
}
public void addAlternative(String alternative){
if(alternatives == null){
alternatives = new String[N_POSSIBLE_ANSWERS];
}
alternatives[nAddedAlternatives] = alternative;
nAddedAlternatives++;
}
public void clearAlternatives(){
nAddedAlternatives = 0;
alternatives = null;
}
public String getAlternative(int i){
//String result = ALTERNATIVE_CAPTIONS[i];
//result += ": ";
String result = alternatives[i];
return result;
}
public int getAnswer(){
return answerID;
}
public void setAnswer(int answer){
answerID = answer;
}
}
The ElementArray defined as "alternatives" is the interest point of this question.
Best regards,
fercis
Please use the below method to convert that
public static void convert(InputStream inputStream,OutputStream outputStream,List<String> result) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringElementContentWhitespace(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(inputStream);
if(inputStream != null)
inputStream.close();
NodeList childNodes = document.getChildNodes().item(0).getChildNodes();
Document writeDoc = builder.newDocument();
Element rootElement = writeDoc.createElement(document.getChildNodes().item(0).getNodeName());
for (int i = 0; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
if(result.contains(item.getNodeName())) {
System.out.println("Skipped ...");
continue;
}
Node node = item.cloneNode(true);
writeDoc.adoptNode(node);
rootElement.appendChild(node);
}
writeDoc.appendChild(rootElement);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(writeDoc);
transformer.transform(source, new StreamResult(outputStream));
} catch (Exception e) {
e.printStackTrace();
}
}
This is the method which take the input as a InputStream, will return result in OutPutStream, will accept List of String that need to be filtered.
I am trying to Parse the below XML file and create an JTree based on it.
<OBJECTS>
<WINDOW NAME = "WINDOW 01" URL = "URL 01">
<PAGE NAME = "PAGE 01" URL = "PAGE URL 01">
</PAGE>
</WINDOW>
</OBJECTS>
The "WINDOW 01" is getting added to the root node "Object List", but the "PAGE 01" node is not getting displayed under the "WINDOW 01" node. The source code used is given below. Please Help!!!
public class DataNode extends DefaultMutableTreeNode {
private static final long serialVersionUID = 1L;
public String ObjectType, ObjectName, URL, ElementType;
public DefaultMutableTreeNode node;
public DataNode(DefaultMutableTreeNode node, Element element) {
this.node = node;
this.ObjectType = element.getTagName();
this.ObjectName = element.getAttribute("NAME");
this.URL = element.getAttribute("URL");
this.ElementType = element.getAttribute("TYPE");
}
public DataNode(Element element) {
this.node = new DefaultMutableTreeNode("OBJECT");
this.ObjectType = element.getTagName();
this.ObjectName = "Object List";
this.URL = "";
this.ElementType = "";
}
#Override
public String toString() {
return this.ObjectName;
}
}
This is the main class. No errors or warnings are displayed on compiling.
public class MyOwn {
private JFrame contentsFrame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyOwn window = new MyOwn();
window.contentsFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public MyOwn() {
contentsFrame = new JFrame();
contentsFrame.setTitle("My JTree");
contentsFrame.setBounds(100, 100, 549, 738);
contentsFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTree objectListTree = new JTree(convertXMLtoTree("G:/Collection.xml"));
objectListTree.setAlignmentY(Component.TOP_ALIGNMENT);
objectListTree.setAlignmentX(Component.LEFT_ALIGNMENT);
contentsFrame.getContentPane().add(new JScrollPane(objectListTree));
}
private DefaultMutableTreeNode convertXMLtoTree(String Path) {
NodeList nWindow, nPage;
DefaultMutableTreeNode dRoot, dWindow, dPage;
DataNode xRoot, xWindow, xPage;
try {
File fXmlFile = new File(Path);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
xRoot = new DataNode(doc.getDocumentElement());
dRoot = new DefaultMutableTreeNode(xRoot);
nWindow = doc.getDocumentElement().getElementsByTagName("WINDOW");
for (int i = 0; i < nWindow.getLength(); i++) {
dWindow = new DefaultMutableTreeNode(((Element)(nWindow.item(i))).getAttribute("NAME"));
xWindow = new DataNode(dWindow, (Element)(nWindow.item(i)));
dRoot.add(xWindow);
nPage = ((Element)(nWindow.item(i))).getElementsByTagName("PAGE");
for (int j = 0; j < nPage.getLength(); j++) {
dPage = new DefaultMutableTreeNode(((Element)(nPage.item(j))).getAttribute("NAME"));
xPage = new DataNode(dPage, (Element)(nPage.item(j)));
dWindow.add(xPage);
}
}
return dRoot;
} catch (Exception e) {
return null;
}
}
}
Add your custom DefaultMutableTreeNode DataNode to child node for WINDOW 01 rather than the dWindow which never gets added to the JTree. Replace
dWindow.add(xPage);
with
xWindow.add(xPage);
I have a problem with my parser in my android phone!
here is the code for the XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<file>
<Staff>
<connection>wifi</connection>
<timestamp>20</timestamp>
<sport>0</sport>
</Staff>
<Staff>
<connection>3g</connection>
<timestamp>40</timestamp>
<sport>0</sport>
</Staff>
<Staff>
<connection>wifi</connection>
<timestamp>60</timestamp>
<sport>0</sport>
</Staff>
<Staff>
<connection>3g</connection>
<timestamp>80</timestamp>
<sport>0</sport>
</Staff>
</file>
and here is the parser code that i have
try {
InputStream filename = null;
Document obj_doc = null;
DocumentBuilderFactory doc_build_fact = null;
DocumentBuilder doc_builder = null;
filename = new FileInputStream("/sdcard/data.xml");
doc_build_fact = DocumentBuilderFactory.newInstance();
doc_builder = doc_build_fact.newDocumentBuilder();
System.out.println("readed data.xml");
obj_doc = doc_builder.parse(filename);
NodeList obj_nod_list = null;
if (null != obj_doc) {
org.w3c.dom.Element feed = obj_doc.getDocumentElement();
obj_nod_list = feed.getElementsByTagName("file");
}
Element root = obj_doc.getDocumentElement();
NodeList items = root.getElementsByTagName("Staff");
System.out.println("items "+items.getLength());
for (int i = 0; i < items.getLength(); i++) {
Node item = items.item(i);
NodeList properties = item.getChildNodes();
System.out.println("properties length "+item.getChildNodes().getLength());
// System.out.println("properties "+properties.getLength());
for (int j = 0; j < items.getLength(); j++) {
Node property = properties.item(j);
// System.out.println("properties "+property.getNodeName());
String name = property.getNodeName();
if (name.equalsIgnoreCase("connection")) {
// Store it where you want
connection.add(property.getFirstChild().getNodeValue());
System.out.println("connection "+connection);
// System.out.println("connection "+connection.get(i));
}
if (name.equalsIgnoreCase("timestamp")) {
int inttimestamp = Integer.parseInt(property.getFirstChild().getNodeValue());
timestamp.add(inttimestamp);
System.out.println("timestamp "+timestamp);
}
if (name.equalsIgnoreCase("sport")) {
int inttimestamp = Integer.parseInt(property.getFirstChild().getNodeValue());
capacity.add(inttimestamp);
System.out.println("capacity "+capacity);
}
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
when the parsing is done! it can't read the last child! which is sport! can you provide me a solution for it! Also when i change the xml and put the "sport" first, after it can't read the last node! thanks
Use jsoup html parser. Here is the official site. You can use it parsing html, xml etc. It's a tag based parser.
here is an example using the SAX parser it can help you
the parser class:
public class XMLParser extends DefaultHandler
{
// xml Tags name
private final String TENDER_TYPE = "TenderType";
private final String TRX_TYPE = "TransactionType";
private final String DATA_ELEM = "DataElement";
//xml Values
private final String NAME = "Name";
private final String VALUE = "Value";
private final String AMOUNT = "Amount";
private final String T_TYPE = "TenderType";
private final String CLRK_ID = "ClerkId";
private final String INV_NUM = "InvoiceNum";
private final String AUTH = "Authorization";
private final String ORIG_SEQ = "OriginalSequence";
private final String ORIG_REF = "OriginalReference";
private final String TAG = "Tag";
private final String DESCRIPTION = "Description";
//list for imported Config data
private ArrayList<TenderType> theTenderTypeList = null;
private TenderType currentTenderType = null;
private ArrayList<TransactionType> theTrxTypeList = null;
private TransactionType currentTrxType = null;
private ArrayList<DataElement> theDataElementList = null;
private DataElement currentDataElement = null;
#Override
public void startDocument() throws SAXException
{
super.startDocument();
if(theTenderTypeList == null)
{
theTenderTypeList = new ArrayList<TenderType>();
}
if(theTrxTypeList == null)
{
theTrxTypeList = new ArrayList<TransactionType>();
}
if(theDataElementList == null)
{
theDataElementList = new ArrayList<DataElement>();
}
}
#Override
public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException
{
if (localName.equalsIgnoreCase(TRX_TYPE))
{
this.currentTrxType = new TransactionType(attributes.getValue(NAME),
attributes.getValue(VALUE),attributes.getValue(AMOUNT),
attributes.getValue(T_TYPE),attributes.getValue(CLRK_ID),
attributes.getValue(INV_NUM), attributes.getValue(AUTH),
attributes.getValue(ORIG_SEQ), attributes.getValue(ORIG_REF));
this.theTrxTypeList.add(currentTrxType);
}
else if (localName.equalsIgnoreCase(TENDER_TYPE))
{
this.currentTenderType = new TenderType(attributes.getValue(NAME),
attributes.getValue(VALUE));
theTenderTypeList.add(currentTenderType);
}
else if (localName.equalsIgnoreCase(DATA_ELEM))
{
this.currentDataElement = new DataElement(attributes.getValue(TAG),
attributes.getValue(DESCRIPTION));
theDataElementList.add(currentDataElement);
}
}
public ArrayList<TenderType> getTenderTypeList()
{
return theTenderTypeList;
}
public ArrayList<TransactionType> getTrxTypeList()
{
return theTrxTypeList;
}
public ArrayList<DataElement> getDataElementList()
{
return theDataElementList;
}
}
and then u can call it:
SAXParserFactory fabrique = SAXParserFactory.newInstance();
SAXParser parseur = null;
try
{
parseur = fabrique.newSAXParser();
}
catch (ParserConfigurationException e)
{
System.out.println("Parse Config Exception");
}
catch (SAXException e)
{
System.out.println("SAX Parse Exception");
}
handler = new XMLParser();
try
{
/* Parse Config File */
myFileCfg = new File(FolderPath + CFG_FILE_NAME);
parseur.parse(myFileCfg, handler);
}
catch (SAXException e)
I solved it! it was bad the XML file structure! After i changed it! it worked. thanks for your awnsers