Remove XML Nodes as per user input - c#

I am trying to write all the dropped elements prperties in a xml document to save in the database.When the user delete a dropped element ,i need to remove that element from the Xml doc.
XmlDocument oXmlDocument = new XmlDocument();
oXmlDocument.Load(#"D:\VanithaApps\SenMail\DiagramData.xml");
Boolean nodeExits = false;
XmlNode oXmlRootNode = oXmlDocument.SelectSingleNode("records");
XmlNodeList xmlnode = oXmlDocument.GetElementsByTagName("record");
if (delete=="1")
{
if (xmlnode.Count > 0)
{
for (int i = 0; i < xmlnode.Count; i++)
{
string tempVar = element.Substring(0, element.Length - 1);
if (xmlnode[i].ChildNodes[2].InnerText == tempVar)
{
try
{
oXmlRootNode.RemoveChild(xmlnode[i]);
goto Found;
}
catch(Exception ex)
{
ex.ToString();
}
}
}
}
}
if (xmlnode.Count > 0)
{
for (int i = 0; i < xmlnode.Count; i++)
{
string tempVar = element.Substring(0, element.Length-1);
if (xmlnode[i].ChildNodes[2].InnerText == tempVar)
{
nodeExits = true;
XmlNode XAxis = xmlnode[i].ChildNodes[0];
XAxis.InnerText = Convert.ToString(x);
XmlNode YAxis = xmlnode[i].ChildNodes[1];
YAxis.InnerText = Convert.ToString(y);
}
}
if (nodeExits == false)
{
CreateNewNode(x, y, element, userid, oXmlDocument, oXmlRootNode);
}
}
else
{
CreateNewNode(x, y, element, userid, oXmlDocument, oXmlRootNode);
}
Found:
int result = 0;
return result;
I haven't used xml extensively before
<?xml version="1.0" encoding="utf-8"?>
<records>
<record>
<X-Cordinate>774</X-Cordinate>
<Y-Cordinate>173</Y-Cordinate>
<Element>drag595</Element>
<UserID>1</UserID>
</record>
</records>
i want to delete whose child 'Element' value is equal to tempVar.Here if the Element value is equal to drag595 ,i want to remove that entry from my XML .

Change
oXmlRootNode.RemoveChild(xmlnode[i]);//not working//
to
xmlnode[i].ParentNode.RemoveChild(xmlnode[i]);
Children can only be removed from their respective parents.

Related

Aspose.Word MailMerge set font in paragraph

In FieldMergingCallback.FieldMerging and I set font to all Runs in Node =>
public void FieldMerging(FieldMergingArgs args)
{
if (args.FieldValue.ToString().Length > 100)
{
var node = args.Field.Start.ParentNode.ParentNode;
if (node is Shape)
{
var runlist = node.GetChildNodes(NodeType.Run, true);
foreach (Run run in runlist)
{
run.Font.Size = 6;
}
}
}
}
But in result pdf is:
Why is the font smaller than the third word?
Before performing mail merge, you can use the following code to apply same formatting to all Run nodes inside a merge field.
Document doc = new Document("D:\\temp\\input.docx");
foreach (Field field in doc.Range.Fields)
{
if (field.Type.Equals(Aspose.Words.Fields.FieldType.FieldMergeField))
{
Node currentNode = field.Start;
bool isContinue = true;
while (currentNode != null && isContinue)
{
if (currentNode.NodeType.Equals(NodeType.FieldEnd))
{
FieldEnd end = (FieldEnd)currentNode;
if (end == field.End)
isContinue = false;
}
if (currentNode.NodeType.Equals(NodeType.Run))
{
Run run = ((Run)currentNode);
run.Font.Size = 6;
}
Node nextNode = currentNode.NextPreOrder(currentNode.Document);
currentNode = nextNode;
}
}
}
doc.Save("D:\\Temp\\18.6.docx");
Hope, this helps. I work with Aspose as Developer Evangelist.

Docx - Removing section of document

Is there a way to remove sections of a document where i can specify the beginning and ending tags?
i need a way that i can remove a section of the document by passing in both my start and end catches, (##DELETEBEGIN and ##DELETEEND)
for example i have this in my document:
Hello, welcome to this document
##DELETEBEGIN{Some values to check in the code}
Some text that will be removed if the value is true
##DELETEEND
Final Line
If you need to delete text from ##DELETEBEGIN to ##DELETEEND, where ##DELETEBEGIN is not at the beginning of a Paragraph and ##DELETEEND is not at the end of a Paragraph, this code should work.
DocX document = DocX.Load("C:\\Users\\phil\\Desktop\\text.docx");
bool flag = false;
List<List<string>> list1 = new List<List<string>>();
List<string> list2 = new List<string>();
foreach (Novacode.Paragraph item in document.Paragraphs)
{
//use this if you need whole text of a paragraph
string paraText = item.Text;
var result = paraText.Split(' ');
int count = 0;
list2 = new List<string>();
//use this if you need word by word
foreach (var data in result)
{
string word = data.ToString();
if (word.Contains("##DELETEBEGIN")) flag = true;
if (word.Contains("##DELETEEND"))
{
flag = false;
list2.Add(word);
}
if (flag) list2.Add(word);
count++;
}
list1.Add(list2);
}
for (int i = 0; i < list1.Count(); i++)
{
string temp = "";
for (int y = 0; y < list1[i].Count(); y++)
{
if (y == 0)
{
temp = list1[i][y];
continue;
}
temp += " " + list1[i][y];
}
if (!temp.Equals("")) document.ReplaceText(temp, "");
}
document.Save();
I have to give some credit to this post for looping through each word.
I think i have found a solution to this, at least it works for me, please let me know if there is anything i can do better:
the deleteCommand would be the ##DELETEBEGIN string and the deleteEndCommand would be the ##DELETEEND
private void RemoveSection(DocX doc, string deleteCommand, string deleteEndCommand)
{
try
{
int deleteStart = 0;
int deleteEnd = 0;
//Get the array of the paragraphs containing the start and end catches
for (int i = 0; i < doc.Paragraphs.Count; i++)
{
if (doc.Paragraphs[i].Text.Contains(deleteCommand))
deleteStart = i;
if (doc.Paragraphs[i].Text.Contains(deleteEndCommand))
deleteEnd = i;
}
if (deleteStart > 0 && deleteEnd > 0)
{
//delete from the paraIndex as the arrays will shift when a paragraph is deleted
int paraIndex = deleteStart;
for (int i = deleteStart; i <= deleteEnd; i++)
{
doc.RemoveParagraphAt(paraIndex);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}

How Do I Solve Object Reference Not Set To An Instance Of An Object

Am trying to loop through xmlnodes. but getting this error "Object reference not set to an instance of an object." My main goal was to loop it through the datgridviewcell but i don't know how i can take it further. I know the column indexes for font,date and comment from my grid. how can i loop through those column indexes and be able to parse the value to string?
<?xml version="1.0" encoding="utf-8"?>
<root>
<data name="Button"xml:space="preserve">
<value></value>
<comment>[Font][/Font][DateStamp][/DateStamp[Comment][/Comment]</comment>
</data>
XmlNodeList _Nodelist = _doc.SelectNodes("/root");
foreach(XmlNode _Xnode in _Nodelist)
{
XmlNode _data = _Xnode.SelectSingleNode("data");
XmlNodeList _CommentNodes = _data.SelectNodes("comment");
if(_CommentNodes != null)
{
foreach(XmlNode node in _CommentNodes)
{
XmlNode _comment = node.SelectSingleNode("comment");
{
string _font = _comment["Font"].InnerText; //it throws the error here
string _Date = _comment["DateStamp"].InnerText;
string _Comment = _comment["Comment"].InnerText;
}
}
}
}
Your problems are that
There is only one level of <comment> node, but you are looking for nested comment nodes.
The text inside the <comment> node isn't XML - it's just text content. Thus it cannot be parsed as if it contained child XML elements.
Instead you need to do something like the following:
XmlNodeList _Nodelist = _doc.SelectNodes("/root");
foreach (XmlNode root in _Nodelist)
{
XmlNode _data = root.SelectSingleNode("data");
if (_data == null)
continue;
XmlNodeList _CommentNodes = _data.SelectNodes("comment");
foreach (XmlNode _comment in _CommentNodes)
{
var text = _comment.InnerText;
// text = "[Font][/Font][DateStamp][/DateStamp[Comment][/Comment]"
string _font = text.Between("[Font]", "[/Font]", StringComparison.Ordinal);
string _Date = text.Between("[DateStamp]", "[/DateStamp]", StringComparison.Ordinal);
string _Comment = text.Between("[Comment]", "[/Comment]", StringComparison.Ordinal);
}
}
Using the extension method:
public static class TextHelper
{
public static string Between(this string input, string start, string end, StringComparison comparison)
{
var startIndex = input.IndexOf(start, comparison);
if (startIndex < 0)
return null;
startIndex += start.Length;
var endIndex = input.IndexOf(end, startIndex, comparison);
if (endIndex < 0)
return null;
return input.Substring(startIndex, endIndex - startIndex);
}
}
Note that _Date will be null because, as #colmde noted, "[/DateStamp" is missing a closing bracket.

Reading value of an XML node

i need to get the value of an Node in an XML File.
My XML file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<PRODUCTS>
<IPHONE>
<NAME>iPhone 5s</NAME>
<MODEL>5s</MODEL>
<PRICE>899</PRICE>
<COLOR>Gold</COLOR>
</IPHONE>
I want to get the text (iPhone 5s) from the file.
I have tried several things I have found on the internet:
protected void Page_Load(object sender, EventArgs e)
{
String[][] products = new String[3][];
int i = 0;
int j = 0;
System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("../XML-Test/Webshop-products.xml");
while (reader.Read()) {
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.LocalName.Equals("NAME"))
{
//Name of product
products[i][j] = reader.ReadInnerXml();
j++;
}
if (reader.LocalName.Equals("MODEL"))
{
//Model
products[i][j] = reader.ReadString();
j++;
}
if (reader.LocalName.Equals("PRICE"))
{
//Price
products[i][j] = reader.Value;
j++;
}
if (reader.LocalName.Equals("COLOR"))
{
//Color
products[i][j] = reader.Value;
j++;
i++;
}
}
}
for (int k = 0; k < products.Length; k++)
{
for (int l = 0; l < products[k].Length; l++)
{
Console.Write(products[k][l]);
}
}
}
No method seems to work. When i run the project (ASP.NET Project) i get the following error:
System.NullReferenceException: Object reference not set to an instance to an object
How can i get the values of the nodes?
You can use Linq To Xml.
Assuming you you have other products like IPHONE under PRODUCTS
var products = XDocument.Load(filename).Root
.Elements()
.Select(x => new
{
Product = x.Name.LocalName,
Name = (string)x.Element("NAME"),
Model = (string)x.Element("MODEL"),
Price = (decimal)x.Element("PRICE"),
Color = (string)x.Element("COLOR")
})
.ToList();
I suggest to use Linq to Xml:
var xdoc = XDocument.Load("../XML-Test/Webshop-products.xml");
var p = xdoc.Root.Element("IPHONE"); // get first IPHONE from file
if (iPhoneElement == null)
return; // handle case when there is no IPHONE in xml file
var iPhone = new {
Name = (string)p.Element("NAME"),
Model = (string)p.Element("MODEL"),
Price = (decimal)p.Element("PRICE"),
Color = (string)p.Element("COLOR")
};
Then you can use name, model, price or color of iPhone object. E.g.
iPhone.Name
Note - if there is many iPhones in file, you can grab them all:
var iPhones = from p in xdoc.Root.Elements("IPHONE")
select new {
Name = (string)p.Element("NAME"),
Model = (string)p.Element("MODEL"),
Price = (decimal)p.Element("PRICE"),
Color = (string)p.Element("COLOR")
};
You may also want to have a look at the methods given below.
1) XmlDocument and XmlNode
2) Serialization and Deserialization.
3) Simplified example of Serialization and Deserialization

How to display treenodes by binding nodes in the treeview to nodes of the XML document

I have a Treeview where on selecting a node the attributes and values has to be displayed in listbox.
In treeView1_AfterSelect, the text parsing code depends on the textual representation for a node in the tree view, which can be changed at any time and break the entire logic of list display. This strong dependency between the tree view and the list display should be eliminated by binding nodes in the treeview to nodes of the XML document, so that the raw Xml data can be used to display text in the list.What should i write here?
private static void AddingNodesToTree(XmlNode xmlNode,TreeNode tnode)
{
//Adding nodes to tree while looping through the entire XML file
if (xmlNode.HasChildNodes)
{
XmlNodeList nodeList = xmlNode.ChildNodes;
for (int i = 0; i <= nodeList.Count - 1; i++)
{
XmlNode xmladdtreeNode = xmlNode.ChildNodes[i];
String nodetype = "" + xmladdtreeNode.NodeType;
if (nodetype.Equals("Text") || nodetype.Equals("Comment"))
{
tnode.Nodes.Add(new TreeNode(xmladdtreeNode.InnerText));
}
else
{
String name = "<" + xmladdtreeNode.Name;
XmlAttributeCollection attCol = xmladdtreeNode.Attributes;
foreach (XmlAttribute xmlatt in attCol)
{
name += " " + xmlatt.Name + "=\"" + xmlatt.Value + "\"";
}
name += ">";
TreeNode tn = new TreeNode(xmladdtreeNode.Name);
tn.Text = name;
tnode.Nodes.Add(tn);
TreeNode treeNode = tnode.Nodes[i];
AddingNodesToTree(xmladdtreeNode,treeNode);
}
}//for
}//if
else
{
tnode.Text = xmlNode.OuterXml.Trim();
}//else
}//AddingNodesToTree
//To show Attributes and values of selected Nodes.
private void treeView1_AfterSelect(object sender,TreeViewEventArgs e)
{
TreeNode treenode = e.Node; //Node selected in Treeview
String text = treenode.Text;
String relevent = text;
Boolean flag = true;
while (flag)
{
int SpaceIndex = relevent.IndexOf(" ");
if (SpaceIndex != -1)
{
int indexofEqual = relevent.IndexOf('=', SpaceIndex);
if (indexofEqual != -1)
{
int indexOFValue = relevent.IndexOf("\"", indexofEqual + 2);
if (indexOFValue != -1)
{
String attribute = relevent.Substring(SpaceIndex + 1, indexofEqual - SpaceIndex - 1);
String value = relevent.Substring(indexofEqual + 2, indexOFValue - indexofEqual - 2);
listBox1.Items.Add("Attribute : " + attribute + " Value : " + value);
relevent = relevent.Substring(indexOFValue);
}
else
{
listBox1.Items.Add("Bad format of the xml file for this node");
flag = false;
}
}
else
{
flag = false;
}
}
else
{
flag = false;
}
}
}//AfterSelect()
Thanks....
If I understand the question correctly you want to get back to the XmlNode when a TreeNode is selected. The usual solution is to store the XmlNode in the Tag property:
TreeNode tn = new TreeNode();
tn.Text = name;
tn.Tag = xmladdtreeNode;
and in the AfterSelect
TreeNode treenode = e.Node;
XmlNode xmlNode = (XmlNode) treeNode.Tag;
i tried this but got the NullRefrenceException at this line
foreach (XmlAttribute xmlatt in attCol) on attcol
This is the code i have written..
private void treeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
listBox1.Items.Clear();
XmlNode xNode = e.Node.Tag as XmlNode;
XmlAttributeCollection attCol = xNode.Attributes;
foreach (XmlAttribute xmlatt in attCol)
{
listBox1.Items.Add(xmlatt.Name);
listBox1.Items.Add(xmlatt.Value);
}
} //AfterSelect()

Categories

Resources