In the following code, I am trying to do a text parsing by using a streamreader. This is to get the email address from the text file. If i have no email address, combobox is left blank (index = -1). If i have a email that is found in my xml file, then i will select it. Else, i will add a node to my xml file with the new email address.
code:
private void Textparsing()
{
using (StreamReader sr = new StreamReader(Masterbuildpropertiespath))
{
while (sr.Peek() >= 0)
if (line.StartsWith("Builder_Email:"))
{
string[] fields = line.Split('\t');
string builderemail = fields[3];
XmlDocument emailparse = new XmlDocument();
emailparse.LoadXml(#"C:\GUI\buildermanageremail.xml");
XmlNodeList emailnode = emailparse.GetElementsByTagName("value");
if (string.IsNullOrEmpty(builderemail))
comboBox1.SelectedIndex = -1;
else
foreach (XmlNode node in emailnode)
{
if (builderemail == node.InnerText)
{
int count = emailparse.SelectNodes("email/builderemail/builder").Count;
count--;
comboBox1.SelectedIndex = count;
}
else
{
//create main node
XmlNode abc = emailparse.CreateNode(XmlNodeType.Element, "builder", null);
//create the first child node
XmlNode value = emailparse.CreateElement("value");
//set the value
value.InnerText = builderemail;
// add childes to father
//node.AppendChild(id);
abc.AppendChild(value);
// find the node we want to add the new node to
XmlNodeList l = emailparse.GetElementsByTagName("builderemail");
// append the new node
l[0].AppendChild(abc);
// save the file
emailparse.Save(#"C:\GUI\buildermanageremail.xml");
//then we populate the new updated xml file into the drop down list:
PopulateDDLFromXMLFile();
int count = emailparse.SelectNodes("email/builderemail/builder").Count;
count--;
comboBox1.SelectedIndex = count;
}
}
}
However, I get an XmlException (Data at the root level is invalid. Line 1, position 1.) at this line:
emailparse.LoadXml(#"C:\GUI\buildermanageremail.xml");
Why is that so?
my xmlfile:
<?xml version="1.0" encoding="utf-8"?>
<email>
<builderemail>
<builder>
<value>abc#123.com</value>
</builder>
<builder>
<value>Others</value>
</builder>
</builderemail>
<manageremail>
<manager>
<value>abc#456.com</value>
</manager>
<manager>
<value>Others</value>
</manager>
</manageremail>
</email>
You should use the
emailparse.Load(#"C:\GUI\buildermanageremail.xml");
method instead of
emailparse.LoadXml(#"C:\GUI\buildermanageremail.xml");
since LoadXml can load xml string, not the file.
Related
I have a JSONArray named DataExtract containing objects like below extracted from a TSV file:
The requirement is to extract the items one by one like extract the value from records1's 0th element : agent_4 and assign to a String named ID, then records1's 1st element and assign it to text and same for records[2]'s 2nd element. And the final output should look like below :
DataExtract = {
ID : agent_4,
text = "Can i text you the information"
count = 1 ,
ID: agent_11,
text = "",
count =2,
}
How can i achieve this ? or there is some other way to store the arraylist information and assign it one by one
Current code which is getting me as one single jsonArray :
List<List<String>> records = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(content))) {
String line;
//todo to check if it is required to be sent via Map or Json Object
while ((line = br.readLine()) != null) {
String[] values = line.split("\t");
records.add(Arrays.asList(values));
}
Gson gson = new Gson();
String jsonArray = gson.toJson(records);
logger.debug("Print value{}", jsonArray);
JSONObject obj = new JSONObject();
obj.put("Data:", jsonArray);
for(int i =0;i<jsonArray.size();i++) { //for jsonArray
for(int j=0;j<i;j++) { //inner loop for each elements
String candidateID=String.valueOf(jsonArray.get(j));
} //but it is getting the entire string not separate elements like i want to extract agent_4 only in this string , the split is also not working
Worked with JSONObject:
Load file by BufferedReader and use JsonArray to format your Json output
BufferedReader reader = new BufferedReader(new FileReader("data.tsv"));
String[] fieldNames = reader.readLine().split("\t");
List<JSONObject> rows = new ArrayList<>();
// Read tsv file line by line
String line;
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\t");
JSONObject row = new JSONObject();
for (int i = 0; i < fieldNames.length; i++) {
row.put(fieldNames[i], fields[i]);
}
rows.add(row);
}
reader.close();
// Convert the list of rows to a JSON array
JSONArray array = new JSONArray(rows);
I was wondering if it was possible with a TreeView in a windows form to add or remove a level?
For example:
my treeview is like this to begin with:
ParentNode
| Child1
| Child2
if user clicks on a button to add a level to Child2 it becomes:
ParentNode
| Child1
| | Child1.1
There is a a Node.Level function but only usable to get the level and not to set it.
EDIT:
The nodes are built automatically, the level is assigned depending on the style of an excel cell. The problem is, it happens that the created node is not at it's correct place because the excel file is not well made. So I see 2 options o resolve this problem:
1- the user modifies the excel file directly
2- I create a Move Left Move Right button on a selection of nodes.
I'd like to offer the 2nd possibility.
Here's the code I used to build the nodes:
public static void AddNodes(Excel.Application app,
TreeView treeView)
{
Excel.Range selection = app.Selection;
ArrayList style = new ArrayList();
TreeNode parentNode = treeView.SelectedNode;
//Selected Node => Last used node
for (int i = 1; i <= selection.Rows.Count; i++)
{
TreeNode tn;
int fontSize = Convert.ToInt32(selection.Cells[i].Font.Size);
if (!style.Contains(fontSize))
{
style.Add(fontSize);
}
else if (style[style.Count - 1].Equals(fontSize))
{
try
{
treeView.SelectedNode = treeView.SelectedNode.Parent;
}
catch (Exception x)
{
ErrorBox(x);
}
}
else
{
int indexPreviousCellofSameColor = style.IndexOf(fontSize);
//Select TN parent
for (int j = 1; j <= (style.Count - indexPreviousCellofSameFont); j++)
{ treeView.SelectedNode = treeView.SelectedNode.Parent; }
style.RemoveRange(indexPreviousCellofSameFont + 1, style.Count - indexPreviousCellofSameFont - 1);
}
if (selection.Cells[i].Value2 == null)
{
//if empty cell, do something ... or nothing
treeView.SelectedNode = treeView.SelectedNode.LastNode;
}
else
{
//Add new TN to parent - TN object corresponds to excel cell
tn = new TreeNode()
{
Text = selection.Cells[i].Value2,
Tag = selection.Cells[i],
};
treeView.SelectedNode.Nodes.Add(tn);
tn.ToolTipText = tn.Level.ToString();
//selected TN => created TN
treeView.SelectedNode = tn;
}
}
}
I had to change my answer completely to the changed question.
This seems to do the job in my tests. It moves the selected node to a new level, under the one that was just above it.
It needs more checks offcourse to make sure your not moving nodes to oblivion...
private void button1_Click(object sender, EventArgs e)
{
TreeNode selected = treeViewFilter.SelectedNode;
TreeNode parent = selected.Parent;
// find the node just above the selected node
TreeNode prior = parent.Nodes[selected.Index - 1];
if (parent != prior)
{
treeViewFilter.Nodes.Remove(selected);
prior.Nodes.Add(selected);
}
}
I have a problem with C# read(){} function. When I open and read my document it does not read the first line:
private static void read(string file, Konteineris butas)
{
using (StreamReader reader = new StreamReader(#file))
{
string line;
line = reader.ReadLine();
while (null != (line = reader.ReadLine()))
{
string[] values = line.Split(';');
int nr = Convert.ToInt16(values[0]);
double plotas = Convert.ToDouble(values[1]);
int kambariusk = Convert.ToInt16(values[2]);
int kaina = Convert.ToInt32(values[3]);
string tnr = values[4];
Apartaments apart = new Butas(nr,plotas,kambariusk,kaina,tnr); // array of apartaments
apartaments.addapartament(apart);
}
}
}
the text file:
1;25,4;1;25000;867467212 // skips this line...
2;26,4;2;100000;867467212
3;75,4;3;2100;867467212
4;65,4;4;15000;867467212
Remove the first call to line = reader.ReadLine(); You are calling ReadLine() your loop, so you don't need it there.
Because you do a line = reader.ReadLine(); then follow it up with the same code in the while loop, by the time it hits it's first iteration of the loop, it's already done a .ReadLine() twice, thus is on the second line of the file.
Remove the line = reader.ReadLine(); from the code and retry.
private static void read(string file, Konteineris butas)
{
using (StreamReader reader = new StreamReader(#file))
{
string line;
line = reader.ReadLine();
while (null != (line = reader.ReadLine()))
{
string[] values = line.Split(';');
int nr = Convert.ToInt16(values[0]);
double plotas = Convert.ToDouble(values[1]);
int kambariusk = Convert.ToInt16(values[2]);
int kaina = Convert.ToInt32(values[3]);
string tnr = values[4];
Apartaments apart = new Apartaments(nr,plotas,kambariusk,kaina,tnr); // array of apartaments
apartaments.addapartament(apart);
}
}
}
remove this. since your while condition does this already and you will jump over the first line based on this call.
line = reader.ReadLine(); gives you a new line every time you call it.
So in your while condition you get your second line without using your first.
way1:
private static void read(string file, Konteineris butas)
{
using (StreamReader reader = new StreamReader(#file))
{
string line;
while (null != (line = reader.ReadLine()))
{
string[] values = line.Split(';');
int nr = Convert.ToInt16(values[0]);
double plotas = Convert.ToDouble(values[1]);
int kambariusk = Convert.ToInt16(values[2]);
int kaina = Convert.ToInt32(values[3]);
string tnr = values[4];
Apartaments apart = new Apartaments(nr,plotas,kambariusk,kaina,tnr); // array of apartaments
apartaments.addapartament(apart);
}
}
}
way2:
private static void read(string file, Konteineris butas)
{
using (StreamReader reader = new StreamReader(#file))
{
string line;
while (line!=null)
{
line = reader.ReadLine();
string[] values = line.Split(';');
int nr = Convert.ToInt16(values[0]);
double plotas = Convert.ToDouble(values[1]);
int kambariusk = Convert.ToInt16(values[2]);
int kaina = Convert.ToInt32(values[3]);
string tnr = values[4];
Apartaments apart = new Apartaments(nr,plotas,kambariusk,kaina,tnr); // array of apartaments
apartaments.addapartament(apart);
}
}
}
This question already has answers here:
how to read all cell value using Apache POI?
(2 answers)
Closed 7 years ago.
I had created my script to validate my actual result and expected result , .
As there is too many link to validated script will get too much of coding m so i need to convert this into Data Driven Case ,.
Where Webdriver will get URL , xpath ,expected value from excel .
But dont know how to proceed , .
A demo code is much appreciated
Here is my current script :
public void test() throws Exception
{
String home_logo_url="158321";
String enough_talk_promo="1057406";
System.out.println("Check for home_logo_url");
driver.get(baseUrl);
String SiteWindow = driver.getWindowHandle(); // get the current window handle
driver.findElement(By.xpath("//*[#id='logo']/a")).click();
for (String PromoWindow : driver.getWindowHandles())
{
driver.switchTo().window(PromoWindow); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
String script = "return rlSerial;";
String value = (String) ((JavascriptExecutor)driver).executeScript(script);
Assert.assertEquals(value,home_logo_url);
driver.close();
driver.switchTo().window(SiteWindow);
System.out.println("Pass");
System.out.println("Check for enough_talk_promo");
driver.get(baseUrl + "/category/tournaments/");
driver.findElement(By.xpath("//*[#id='content']/div/div[4]/aside/div/div/p[1]/a")).click();
for (String PromoWindow : driver.getWindowHandles())
{
driver.switchTo().window(PromoWindow); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}
String sr_enough_talk_promo = (String) ((JavascriptExecutor)driver).executeScript(script);
Assert.assertEquals(sr_enough_talk_promo,enough_talk_promo);
driver.close();
driver.switchTo().window(SiteWindow);
System.out.println("Pass");
}
How to iterated to each rows and get my test case run !!!
It is much helpful , if some one can convert my existing code to work on excel sheet .
Thanks
i was working on a project in Spring that read from an excel (.xls) and this was my code if can help
private List<String> extraire (String fileName) throws IOException {
List<String> liste = new ArrayList();
FileInputStream fis = new FileInputStream(new File(fileName));
HSSFWorkbook workbook = new HSSFWorkbook(fis);
HSSFSheet spreadsheet = workbook.getSheetAt(0);
Iterator < Row > rowIterator = null;
rowIterator = spreadsheet.iterator();
while (rowIterator.hasNext()) {
int i = 0;
row = (HSSFRow) rowIterator.next();
Iterator < Cell > cellIterator = row.cellIterator();
while ( cellIterator.hasNext()) {
Cell cell = cellIterator.next();
i++;
/**
* For verifying if a line is empty
*/
if (i % 29 == 0 || i == 1) {
while ( cellIterator.hasNext() && cell.getCellType() == Cell.CELL_TYPE_BLANK) {
cell = cellIterator.next();
}
}
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
String cellule = String.valueOf(cell.getNumericCellValue());
liste.add(cellule);
break;
case Cell.CELL_TYPE_STRING:
liste.add(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BLANK:
cellule = " ";
liste.add(cellule);
break;
}
}
}
fis.close();
return liste;
}
in my controller :
List<String> liste = new ArrayList();
liste = extraire(modelnom);
for (int m=0, i=29;i<liste.size();i=i+29) {
if(i % 29 == 0) {
// i=i+29 : begin from the second line first coll
// m is line
m++;
}
String matricule = (String)liste.get(29*m).toString().trim();
float mat = Float.parseFloat(matricul); // From String to float
employe.setMatricule((int)mat); //reading mat as an int
// ... your Code
}
Is there a way to search for all document that include a word in the first 10 words of a certain field?
Thanks
If you expect that it will always be the first ten words of a particular field that you are targeting, perhaps you could add a field to your schema.xml that just contains the first ten words of that field.
It would be really easy to write an analyzer with a parameter having the number of max tokens which would filter the remaining tokens making it reusable.
you can easily modify the schema.xml to copy the original field contents to this field and use this field for searching.
Something like this should do it:
public boolean doesWordExist(String word, String path) {
String line = null;
int count = 0;
String token = null;
BufferedReader br = null;
File folder = new File(path);
File[] listOfFiles = folder.listFiles(/*use filename filter here*/);
for (int i = 0; i < listOfFiles.length; i++) {
count=0;
if (listOfFiles[i].isFile()) {
try {
br = new BufferedReader(new InputStreamReader(
new FileInputStream(listOfFiles[i].getName())));
while ((line = br.readLine()) != null && count < 10) {
StringTokenizer tknz = new StringTokenizer(line, "");
while (tknz.hasMoreTokens() && count < 10 /* variable */) {
token = tknz.nextToken();
if (token.equalsIgnoreCase(word)) {
return true;
}
count++;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}// if
}//for
return false;
}