Adding a node in the beginning of XML parent node - c#

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);

Related

Insert node in xml document using c#

I was trying to insert an XML node in XML document at a specific position.
This is my xml:
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<readContract xmlns="http://implementation.company.schema.reference">
<ContactNumbers>10158</ContactNumbers>
<productGroups>0085</productGroups>
<indicationBalanceInfo>false</indicationBalanceInfo>
<indicationBlocked>true</indicationBlocked>
</readContract>
</Body>
</Envelope>
And am trying to insert another tag <productGroups>0093</productGroups> below to the tag <productGroups>0085</productGroups>
Expecting like the below:
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<readContract xmlns="http://implementation.company.schema.reference">
<ContactNumbers>10158</ContactNumbers>
<productGroups>0085</productGroups>
<productGroups>0093</productGroups>
<indicationBalanceInfo>false</indicationBalanceInfo>
<indicationBlocked>true</indicationBlocked>
</readContract>
</Body>
</Envelope>
Used the below C# code to achieve it.
XmlDocument doc = new XmlDocument();
string inputxml = this.StServiceCallActivity5.InputEnvelope.InnerXml.ToString();
//Here inputxml contains whole xml document.
string addxml = "<productGroups>0093</productGroups>";
doc.LoadXml(inputxml);
XmlDocumentFragment xmlDocFrag = doc.CreateDocumentFragment();
xmlDocFrag.InnerXml = addxml;
XmlElement parentEle = doc.DocumentElement;
parentEle.AppendChild(xmlDocFrag);
And it returns value like
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<readContract xmlns="http://implementation.company.schema.reference">
<ContactNumbers>10158</ContactNumbers>
<productGroups>0085</productGroups>
<productGroups>0093</productGroups>
<indicationBalanceInfo>false</indicationBalanceInfo>
<indicationBlocked>true</indicationBlocked>
</readContract>
</Body>
<productGroups xmlns="">0093</productGroups>
</Envelope>
Am a newbie to C# code, kindly help me to get the XML doc as expected.
your help is much appreciated.
When you do this:
XmlElement parentEle = doc.DocumentElement;
parentEle.AppendChild(xmlDocFrag);
You're appending the node to the root of the document. You probably wanted to select the actual readContract node that the item is supposed to be appended into. As an example:
XmlNode newNode = doc.CreateNode(XmlNodeType.Element, "productGroup", "");
newNode.InnerText = "something";
XmlNode readContractNode = doc["Envelope"]["Body"]["readContract"];
XmlElement groups = readContractNode["productGroups"];
readContractNode.InsertAfter(newNode, groups);
Of course you'd probably want to handle the case where there are already multiple child productGroup elements, but the idea is the same.
Looks like namespaces are causing the problem. This worked for me:
XmlDocument doc = new XmlDocument();
doc.LoadXml(File.ReadAllText("XMLFile1.xml"));
XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);
ns.AddNamespace("ns1", "http://schemas.xmlsoap.org/soap/envelope/");
ns.AddNamespace("ns2", "http://implementation.company.schema.reference");
var rootNode = doc.SelectSingleNode("//ns1:Envelope", ns);
var readContractNode = rootNode.FirstChild.FirstChild;
var newNode = doc.CreateNode(XmlNodeType.Element, "productGroups", "http://implementation.company.schema.reference");
newNode.InnerText = "0093";
readContractNode.InsertAfter(newNode, readContractNode.SelectSingleNode("//ns2:productGroups", ns));
Or if you don't fancy namespaces like I me, you can try a bit more "brute-forcy" approach:
XmlDocument doc = new XmlDocument();
doc.LoadXml(File.ReadAllText("XMLFile1.xml"));
var newNode = doc.CreateNode(XmlNodeType.Element, "productGroups", "http://implementation.company.schema.reference");
newNode.InnerText = "0093";
doc.FirstChild.FirstChild.FirstChild.InsertAfter(newNode, doc.FirstChild.FirstChild.FirstChild.FirstChild.NextSibling);
It can be optimized but I think it helps to make the point that root cause is the different namespaces in the document.
You may want to use XmlNode.InsertAfter Method.
public virtual XmlNode InsertAfter(
XmlNode newChild,
XmlNode refChild
)
Where
newChild = The XmlNode to insert
and
refChild = The XmlNode that is the reference node. The newNode is placed after the refNode
Please check this link for information.
And check this link with answer on SO.
P.S.
Always check other answers before posting new question.

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.

inserting xml element into multiple nodes

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);
}

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.

Wrap XmlNode with tags - C#

I have the following xml:
<span>sometext</span>
and I want to wrap this XmlNode with another tag:
<p><span>sometext</span></p>
How can i achieve this. For parsing i use XmlDocument (C#).
The above "best answer" works if you don't care that the new "p" node ends up at the end of the parent. To replace it where it is, use:
string xml = "<span>sometext</span>";
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xml);
// If you have XmlNode already, you can start from this point
XmlNode node = xDoc.DocumentElement;
XmlElement clone = node.Clone();
XmlNode parent = node.ParentNode;
XmlElement xElement = xDoc.CreateElement("p");
xElement.AppendChild(clone);
parent.ReplaceChild(xElement, node);
you can try something like this.
string xml = "<span>sometext</span>";
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(xml);
// If you have XmlNode already, you can start from this point
XmlNode node = xDoc.DocumentElement;
XmlNode parent = node.ParentNode;
XmlElement xElement = xDoc.CreateElement("p");
parent.RemoveChild(node);
xElement.AppendChild(node);
parent.AppendChild(xElement);
You must use the CreateNode(XmlNodeType.Element, "p", "") of XmlDocument.
Then append the old node to the new one with the AppendChild method

Categories