Remove an XML node by its content - c#

I Have a XML file that I want remove a node that it's content is 'test'.
I search entire Google, so doesn't help me or I can't get my answer.
The XML file content is shown below:
<?xml version="1.0" encoding="utf-8"?>
<parent>
<child>C#</child>
<child>VB</child>
<child>VB.net</child>
<child>F#</child>
<child>C++</child>
<child>C</child>
<child>Ruby</child>
<child>Pascal</child>
<child>test</child>
<child>python</child>
</parent>
I can load it to any list. So my address is OK.
But can't remove the node that its content is test.
One of my tried code is:
XmlDocument doc = new XmlDocument();
doc.Load(Address);
XmlNode node = doc.SelectSingleNode("/parent/child[text()='test']");
doc.ParentNode.RemoveChild(node);
doc.Save(Address);
any suggestion will be appreciable.
Update: Thanks to Andrei Vatasescu the correct answer is:
node.ParentNode.RemoveChild(node);
instead of :
doc.ParentNode.RemoveChild(node);

Actually the program as posted originally works fine, there is just one small error: "ParentNode.RemoveChild()" should be called on node instead of doc.

Try this:
foreach (XmlNode node in doc.ChildNodes)
{
if (node.InnerText == "test")
{
doc.RemoveChild(node);
}
}

Related

Modify xml with Xmldocument in C#

I am trying to edit the values of an xml document following the instructions found on another post here How to modify existing XML file with XmlDocument and XmlNode in C# .
here is my code
XmlDocument xml = new XmlDocument();
xml = xml.Load(#"https://www.aade.gr/sites/default/files/2020-09/SampleXML_1.1%20%20%28%CE%A4%CE%99%CE%9C-%CE%A0%CE%A9%CE%9B%CE%97%CE%A3%CE%97%CE%A3_%CE%91%CE%A5%CE%A4%CE%9F%CE%A4%CE%99%CE%9C%29%20.xml");
XmlNodeList aNodes = xml.SelectNodes("/InvoicesDoc/invoice/issuer/vatNumber");
foreach (XmlNode aNode in aNodes)
{
XmlAttribute vatAttribute = aNode.Attributes["vatNumber"];
vatAttribute.Value = "123456789";
}
xml.Save(#"C:\Users\Kostas\Desktop\mydata\infinal.xml");
My problem is that XmlNodeList aNodes will return empty; i have tried to change the xml.SelectNodes("/InvoicesDoc/invoice/issuer/vatNumber") to xml.SelectNodes("/InvoicesDoc/invoice/issuer") and all the way up to single xml.SelectNodes("/InvoicesDoc") but still XmlNodeList aNodes will return empty.
First attempts i loaded the XML doc from file and had the issue. Then i thought maybe something wrong with the file so changed the load of the file directly from the site provides this xml template i need to work on. Both options will load the file fine as i can see it when is saved but my changes will not complete since aNodes is empty and foreach loop will skip straight away.
What am i doing wrong?
thanks for your help in advance.
ps this is the xml i need to edit
https://www.aade.gr/sites/default/files/2020-09/SampleXML_1.1%20%20%28%CE%A4%CE%99%CE%9C-%CE%A0%CE%A9%CE%9B%CE%97%CE%A3%CE%97%CE%A3_%CE%91%CE%A5%CE%A4%CE%9F%CE%A4%CE%99%CE%9C%29%20.xml
Update: I just tried with another xlm found in microsoft example called books on https://learn.microsoft.com/en-us/previous-versions/windows/desktop/ms762271(v=vs.85)
XmlNodelist will also return null/empty when i look for /catalog/book . So the good side is that there is no problem with original xml file i need to edit and the bad side is that still i cannot figure out what i am doing wrong.
XmlNodeList aNodes returns null because the xml contains these namespace declarations:
<InvoicesDoc xmlns=\"http://www.aade.gr/myDATA/invoice/v1.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xsi:schemaLocation=\"http://www.aade.gr/myDATA/invoice/v1.0/InvoicesDoc-v0.6.xsd\"
xmlns:icls=\"https://www.aade.gr/myDATA/incomeClassificaton/v1.0\"
xmlns:ecls=\"https://www.aade.gr/myDATA/expensesClassificaton/v1.0\">
You need to manage your xml doing something like this:
XmlDocument xml = new XmlDocument();
xml.Load(#"https://www.aade.gr/sites/default/files/2020-09/SampleXML_1.1%20%20%28%CE%A4%CE%99%CE%9C-%CE%A0%CE%A9%CE%9B%CE%97%CE%A3%CE%97%CE%A3_%CE%91%CE%A5%CE%A4%CE%9F%CE%A4%CE%99%CE%9C%29%20.xml");
XmlNamespaceManager manager = new XmlNamespaceManager(xml.NameTable);
manager.AddNamespace("InvoicesDoc", "http://www.aade.gr/myDATA/invoice/v1.0");
//Example to get the root element
XmlNodeList root = xml.SelectNodes("/InvoicesDoc:InvoicesDoc", manager);
//Example to get the VatNumber tag
XmlNodeList aNodes =xml.SelectNodes("/InvoicesDoc:InvoicesDoc/InvoicesDoc:invoice/InvoicesDoc:issuer/InvoicesDoc:vatNumber", manager);

WPF get every 'secondary child nodes' in a master node

I have the current xml file:
<?xml version="1.0"?>
<Master>
<Child1>
<Display>Some things here</Display>
<Link>http://google.ca</Link>
<Description>Desc</Description>
<Image>http://google.ca</Image>
</Child2>
</Master>
I already figured out how to get the link using doc.SelectSingleNode("Master/Child1/Link").InnerText;
But now, I need a way to list every child (Like Child1, there is way more than that which all have subnodes like link, display....)
I tried a bunch of things but all I found online was how to get "name" from <Master name="Name Here"/>
Also, I'd need it to act as a String (being able to print it to console without getting System.xml.XmlNode)
Thanks for your help.
In xpath * matches any node.
var nodes = doc.SelectNodes("Master/*/Link");
foreach (XmlNode node in nodes)
Console.WriteLine(node.InnerText);
var nodes = doc.SelectNodes("Master/*");
foreach (XmlNode node in nodes)
Console.WriteLine(node.Name);

find if a code exists in xml, using c#

I am starting to work with xml and I am trying to know if there is a way to search a code in this.
Here you are my xml
<?xml version="1.0" encoding="UTF-8"?>
<doctors_hospital>
<doctor>
<code>1757D</code>
<name>one</name>
</doctor>
<doctor>
<code>1169L</code>
<name>two</name>
</doctor>
... continues xml
</doctors_hospital>
I want to look for the code "aab" using c#, and this is my code..
var document =new XmlDocument();
document.Load("O:\\test\\doctor.xml");
XmlNode doctor;
XmlNode root = document.DocumentElement;
doctor = root.SelectSingleNode("/doctors_hospital/doctor/code='aab'");
I can not do this. any suggestion? thanks
Assuming SelectingSingleNode takes a standard XPath expression, what you want to use is
/doctors_hospital/doctor[code='aab']
This will select the entire doctor node with the matching code value.
I agree with Jim, alternatively you could also use Linq to Xml and do this.
XDocument doc = XDocument.Load(filepath);
var codeExist = doc.Descendants("code").Any(x=>(string)x.Value == "1169L");
Check this Demo

How to change the data within elements in a XML file using C#?

I'm kind of new to XML files in C# ASP.NET. I have a XML in the below format:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Installation>
<ServerIP>192.168.20.110</ServerIP>
<DB_Name>USTCKT1</DB_Name>
<Username>jorame</Username>
<Password>Cru$%e20</Password>
<Table_PreFix>TCK</Table_PreFix>
</Installation>
I need to change the values within each element. For example, when an user clicks I should be able to replace 192.168.20.110 with 192.168.1.12.
How can I accomplish this? Any help will be really appreciated.
You should look at using the methods in the XDocument class. http://msdn.microsoft.com/en-us/library/bb301598.aspx
Specifically look at the methods: Load(string) - to load an XML file, Element() - to access a specific element and Save(string) - to save the XML document. The page on Element() has some sample code which can help.
http://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.element.aspx
You can do something like this using the XDocument class:
XDocument doc = XDocument.Load(file.xml);
doc.Element("Installation").Element("ServerIP").Value = "192.168.1.12";
//Update the rest of the elements
doc.Save(file.xml);
More Details
If you run into namespace issues when selecting your elements you will need to include the xml namespace in the XElement selectors eg doc.Element(namspace + "Installation")
In general, you can do it in the following steps:
Create a new XmlDocument object and load the content. The content might be a file or string.
Find the element that you want to modify. If the structure of your xml file is too complex, you can use xpath you find what you want.
Apply your modification to that element.
Update your xml file.
Here is a simple demo:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("file.xml"); // use LoadXml(string xml) to load xml string
string path = "/Installation/ServerIP";
XmlNode node = xmlDoc.SelectSingleNode(path); // use xpath to find a node
node.InnerText = "192.168.1.12"; // update node, replace the inner text
xmlDoc.Save("file.xml"); // save updated content
Hope it's helpful.

why XElement cannot save my xml file to the file?

I want to construct a long xml string and some of its entities are from another xml file read by a dll. In the end, I'd like to save this xml string to a file by XElement.Save(). It cannot save the string to the file.
For example:
XElement root = new XElement("Root");
// .....
root.Save(filename); // <-- wrong!
However, If I do not use the dll, everything is fine. Even I just call the dll and do nothing else, it won't work for me. Can anybody help me? Thanks
For Appending Node into existing XML File:
From beginning,
1) Create one Root.xml file:
<?xml version="1.0" encoding="utf-8"?>
<Main>
</Main>
2) Use this code to Load and Append Nodes:
XElement xml = new XElement("Root");
XDocument xdoc = XDocument.Load("Root.xml");
xdoc.Element("Main").Nodes().Last().AddAfterSelf(xml); //append after the last backup element
xdoc.Save("Root.xml");

Categories