inserting xml element into multiple nodes - c#

I have the following XML
<ROOT>
<FSM338_Container>
<FSM338_Details>
<RunDate>2013-05-29 09:43:00</RunDate>
<Uic>21690</Uic>
<Date>2013-06-10 00:00:00</Date>
<CASHBREAK>199</CASHBREAK>
<CASHLUNCH>199</CASHLUNCH>
</FSM338_Details>
<FSM338_Details>
<RunDate>2013-05-29 09:43:00</RunDate>
<Uic>21690</Uic>
<Date>2013-06-10 00:00:00</Date>
<CASHBREAK>199</CASHBREAK>
<CASHLUNCH>199</CASHLUNCH>
</FSM338_Details>
</FSM338_Container>
<BillingReport>
<RunDate>2013-05-29 09:43:00</RunDate>
<Uic>21690</Uic>
<Date>2013-06-10 00:00:00</Date>
<gaindacd>1</gaindacd>
<docnum>07000F</docnum>
</BillingReport>
<DataElements>
<unitid>12345</unitid>
<fbocost>0.00</fbo>
</DataElements>
</ROOT>
I need to load the xml doc and add in several elements whenever I find the element named "Uic" . In short if I find "Uic" add in the element <someElement>my stuff here</someElement> at the same level as UIC at all locations.
I'Ve used
XmlDocument xDoc = new XmlDocument();
xDoc.Load(#"path_to_xml.xml");
list = xDoc.GetElementsByTagName("Uic");
I used insertBefore to add in my element but I can get it to copy to only the first element

You can use SelectNodes() method of XmlNode which accepts xpath expression.
XmlNodeList nodes = xDoc.DocumentElement.SelectNodes("Uic");
foreach(XmlNode node in nodes) {
XmlElement element = xDoc.CreateElement("SomeElement");
element.InnerText = "anything";
node.ParentNode.AppendChild(element);
}

Related

Add XmlDocument as child node to another XmlDocument

I have two XmlDocuments, one being the root and the other one containing the children. I want to combine them and save them into one document. Currently I have this:
XmlDocument root = new XmlDocument();
root.LoadXml("<tables><table></table></tables>");
XmlDocument childItem = new XmlDocument();
childItem.LoadXml(string.Format(#"<item>
<column columnName=""Article_text"">{0}</column>
<column columnName=""Article_name"">{1}</column>
</item>", atext, aname));
root.AppendChild(childItem);
I want my new document's structure to be tables/table/item. However, the code above throws me an error:
The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type.
var newNode = root.ImportNode(childItem.FirstChild, true);
root["tables"]["table"].AppendChild(newNode);
First import your item element to the root document. Expecting that item is your root node you can use FirstChild and ImportNode to get it:
var newNode = root.ImportNode(childItem.FirstChild, true);
And append it to your table element:
root["tables"]["table"].AppendChild(newNode);

Adding a node in the beginning of XML parent node

I wanted to add a xmlNode in a parent but at the top/beginning. Is there a variant of XMLNode.AppendChild() that i can use?
As far as I understand your question you are probably looking for the XmlNode.PrependChild() method.
Example:
XmlDocument doc = new XmlDocument();
XmlNode root = doc.DocumentElement;
//Create a new node.
XmlElement node = doc.CreateElement("price");
//Add the node to the document.
root.PrependChild(node);
MSDN documentation
I believe the question is asking how to add a node to the beginning of the XML file. I did that in the following manner:
// This is the main xml document
XmlDocument document = new XmlDocument();
// This part is creation of RootNode, however you want
XmlNode RootNode = document.CreateElement("Comments");
document.AppendChild(RootNode);
//Adding first child node as usual
XmlNode CommentNode1 = document.CreateElement("UserComment");
RootNode.AppendChild(commentNode1);
//Now create a child node and add it to the beginning of the XML file
XmlNode CommentNode2 = document.CreateElement("UserComment");
RootNode.InsertBefore(commentNode2, RootNode.FirstChild);

How can i replace the xml elements with new elements in c#

I would like to replace the existing elements inthe xml tag with the new ones.
Sample XML is as follows:
<Dr.Watson>
<Bugs>
<Bug Name="Bug.add --> AAAAAAAAAAAA">
<criteria>
<includeFilterSets>
<filterSet>
<filter>
<filterName>PRODUCT_NAME</filterName>
<operator>
<name>Equals</name>
</operator>
<value>Dr.Watson</value>
</filter>
</filterSet>
</includeFilterSets>
<grouping>
<groupBy>
<name>STATUS</name>
</groupBy>
</grouping>
<caseSensitive>false</caseSensitive>
<entityToSearch>
<name>BUG</name>
</entityToSearch>
</criteria>
</Bug>
</Bugs>
</Dr.Watson>
Code so far i have :
XmlDocument doc = new XmlDocument();
doc.LoadXml(FilePath_EXPRESS_API_InputFile);
XmlNodeList nodelist = doc.SelectNodes("/Dr.Watson/Bugs/Bug");
//create node and add value
//Console.WriteLine(mxpwr.Value);
XmlNode node = doc.CreateNode(XmlNodeType.Element, "grouping", null);
XmlNode node11 = doc.CreateNode(XmlNodeType.Element, "groupBy", null);
XmlNode node12 = doc.CreateNode(XmlNodeType.Element, "name", null);
//Create Title Node
XmlNode Test_11 = doc.CreateElement("grouping");
XmlNode Test_22 = doc.CreateElement("groupBy");
XmlNode Test_44 = doc.CreateElement("name");
//add value for it
Test_11.InnerText = ("");
Test_22.InnerText = ("");
Test_44.InnerText = ("");
//create Url node
//XmlNode Test_445 = doc.CreateElement("sai");
Test_44.InnerText = ("STATE");
//add to parent node
Test_11.AppendChild(Test_22);
Test_22.AppendChild(Test_44);
//add to elements collection
doc.DocumentElement.AppendChild(Test_11);
Test_11.AppendChild(Test_22);
Test_22.AppendChild(Test_44);
Please suggest and help me as i am new to c# for xml scenarios.Thanks.Also, please note that i dont want to save these edits and want to use the edited xml runtime for the execution of APIs.
To replace a node via the XML-DOM API (XmlDocument et al):
Get an instance of XmlNode (or a subclass), parent, representing the parent element of the node you want to replace.
Use parent.RemoveChild to remove the old node.
Use parent.AppendChild to add the new node.
(As an alternative to #3 use parent.InsertAfter or parent.InsertBefore and a reference to another child to place the new node amongst other existing children.)
You code in the question appears to be constructing a new XML document from scratch: why would you want to replace a nodeā€”just create the right one first time. To modify an existing XML document use one of the static XmlDocument.Load methods to load and parse the existing document, use the various search and navigation methods to get the reference in #1 above, then apply the above steps, and finally save as normal.

How to create a path to xml element in C#

I want to create a routing(path) to xml element and assign it to a variable so i can access it
fast in the future.
The element, which is a child of other elements, can change its position in the document
so i cant use methods like first child or indexing that rely on position.
The path to the element will always stay constant and there is no other path like it.
If we look at a short example so i want a path to level4 value(header4) so i can modify it.
<level1>
<level2>
<level3>header3</level3>
<level4>header4</level4>
<level3>header31</level31>
</level2>
<level2>
<level3>nnn</level3>
<level3>nnnnn</level31>
</level2>
</level1>
You've got to use XPath in that case.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Path of the xml");
XmlNode titleNode = xmlDoc.SelectSingleNode("//level1/level2/level3");
You can use XPath for this.
XmlDocument doc; // assuming the xml is already in doc
XmlNode node = doc.SelectSingleNode("/level1/level2/level3/level4");
if(node != null)
{
node.InnerText = "New value";
}
If there could be more than one level4 then you could do this:
XmlDocument doc; // assuming the xml is already in doc
XmlNodeList nodes = doc.SelectNodes("/level1/level2/level3/level4");
if(nodes != null)
{
foreach(XmlNode node in nodes)
{
node.InnerText = "New value";
}
}

How to add and delete an XML node?

I have this code below. I want to add a new node in it to hold more user records and if I want I can remove them. Can anyone help me?
string filename = "text.xml";
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("Login");
XmlElement id = doc.CreateElement("passWord");
root.SetAttribute("userName", nameTxb.Text);
id.SetAttribute("passWord", passwordTxb.Text);
XmlElement name = doc.CreateElement("UserName");
XmlElement passd = doc.CreateElement("PassWord");
name.InnerText = nameTxb.Text;
passd.InnerText = passwordTxb.Text;
root.AppendChild(name);
root.AppendChild(passd);
doc.AppendChild(root);
doc.Save(filename);
MessageBox.Show("Created SuccesFully!");
this.Close();
Your XML document is stored in variable doc. You may use doc.SelectNodes() to select specified nodes using XPATH. You may also iterate over selected nodes and append childs, remove childs etc.
var nodes = doc.SelectNodes("xpath");
foreach(XmlNode node in nodes)
{
//
}
This will remove an element. You can keep using SelectSingleNode() to move down through the branches of the xml. element can also be selected that way - for this example, just consider it an arbitrary starting point.
someElement.RemoveChild(oDoc.SelectSingleNode("Parent").SelectSingleNode("Child"));
As far as I know, you can also use the same method at the XmlDocument level too.
Hope this helps.

Categories