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.
Related
I am new to C#, kindly help me. How to remove the single xml element node 'PaymentRecord' and content inside that should not get deleted.
<Payments>
<PaymentRecord>
<PayId>2031</PayId>
<Reference>Policy03</Reference>
<StatusCode>ACV</StatusCode>
<MethodDetail>
<PaymentMethodDetail>
<CardPaymentDetails>
<CardHolderName>abcded</CardHolderName>
<CardTransactionDetails>
<StoredCard>N</StoredCard>
</CardTransactionDetails>
</CardPaymentDetails>
</PaymentMethodDetail>
</MethodDetail>
<CurrencyCode>USD</CurrencyCode>
</PaymentRecord>
</Payments>
I need to remove "PaymentRecord" element from the XML. I need like below
<Payments>
<PayId>2031</PayId>
<Reference>Policy03</Reference>
<StatusCode>ACV</StatusCode>
<MethodDetail>
<PaymentMethodDetail>
<CardPaymentDetails>
<CardHolderName>abcded</CardHolderName>
<CardTransactionDetails>
<StoredCard>N</StoredCard>
</CardTransactionDetails>
</CardPaymentDetails>
</PaymentMethodDetail>
</MethodDetail>
<CurrencyCode>USD</CurrencyCode>
</Payments>
I have tried my below code, but its deleting the complete node which I don't want to do :- here 'queuePayload' is the xml element
XmlNodeList payloadRecordList = queuePayload.SelectNodes("//Payments/PaymentRecord");
foreach (XmlElement singleNode in payloadRecordList)
{
XmlHelper.removeElem((XmlElement)singleNode.ParentNode, "//PaymentRecord");
XmlDocument xmlDoc = singleNode.OuterXml;
// my remaining logic goes based on "xmldoc" value - I will inserting this data to table
}
You can use System.Xml.Linq with its XDocument to achiev this. Load the input and create a new document out of it like:
XDocument inputDoc = XDocument.Load(inputFile, LoadOptions.None);
XDocument outputDoc = new XDocument();
var elements = inputDoc.Element("Payments").Elements().Select(pr => pr.Elements());
XElement newElement = new XElement("Payments");
foreach (var element in elements)
{
newElement.Add(element);
}
outputDoc.Add(newElement);
Console.WriteLine(outputDoc.ToString());
I think #Fructzwerg is slightly overcomplicating it.
You can remove the PaymentRecord node and add all its children to the root in one go.
var xDoc = XDocument.Load(filePath);
var paymentRecord = xDoc.Root.Element("PaymentRecord");
var nodes = xDoc.Root.Element("PaymentRecord").Elements();
paymentRecord.Remove();
xDoc.Root.Add(nodes);
Console.WriteLine(xDoc.ToString());
dotnetfiddle
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);
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.
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);
}
One of my nodes inmy xml file is as follows.
<LOGIN_ID NAME="Kapil">
<SEARCH_ID>Kapil Koli</SEARCH_ID>
<GUID>111</GUID>
<FIRST_NAME>Kapil</FIRST_NAME>
<LAST_NAME>Koli</LAST_NAME>
<EMAIL_ID>kapil#abc.co.in</EMAIL_ID>
<PASSWORD>abc123**</PASSWORD>
</LOGIN_ID>
The code I am using is -
XmlDocument document = new XmlDocument();
document.Load(_XmlFileName);
nodeList = document.SelectNode."USERS/LOGIN_ID[contains(SEARCH_ID,'Kapil')";
nodeList = document.SelectNode."USERS/LOGIN_ID[contains(EMAIL_ID,'kapil#abc.co.in')";
I want to use select node which will accept search_id and login_id as attributes to search?
If either search_id or email_id is wrong, I want to return null.
How could I do this?
thanks.
kapil.
USERS/LOGIN_ID[contains(SEARCH_ID,'Kapil') and contains(EMAIL_ID,'kapil#abc.co.in')]
should do the trick.