Deletion of a single node in xml using c# - c#

My xml file is as follows:
<Default>
<CareSettingName>
<Name>Hosp1/Name>
<Name>Hosp2/Name>
<Name>Hosp3/Name>
<Name>Hosp4/Name>
</CareSettingName>
<DocNames>
<Name>Doc1/Name>
<Name>Doc2/Name>
<Name>Doc3/Name>
</DocNames>
</Default>
With the following code I try to delete Hosp4:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(localXMLfile);
XmlNode node = xmlDoc.SelectSingleNode("/Default/CareSettingName[Name='Hosp4']");
node.ParentNode.RemoveChild(node);
xmlDoc.Save(localXMLfile);
When I run this, it deletes ALL the entries in CareSettingName - not the single one I am looking for. I can't see to find the problem. Can somebody please help me?
Can anybody please help me? Thanks.

It's because you're selecting /Default/CareSettingName (when it contains a Name that equals Hosp4).
Try changing your xpath to:
/Default/CareSettingName/Name[.='Hosp4']

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

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

Remove an XML node by its content

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

XML namespace and XmlNamespaceManager c#

I've a little problem..
I'm using XmlNamespaceManager to parse a contex with unknown namespace..
It works really fine but I've a problem...
This is a snapshop of the generated XML
<RecordingConfig b:topic="true" xmlns="http://www.onvif.org/ver10/topics" xmlns:b="http://docs.oasis-open.org/wsn/t-1">
<JobState b:topic="true">
...
</JobState>
</RecordingConfig>
It's ok.. but I'd a little change like this:
<tns1:RecordingConfig b:topic="true" xmlns:tns1="http://www.onvif.org/ver10/topics" xmlns:b="http://docs.oasis-open.org/wsn/t-1">
<tns1::JobState b:topic="true">
...
</tns1:JobState>
</tns1:RecordingConfig>
(look the prefix tns1:)
Someone can help me, please?
Thanks in advance
For removing namespace you have to write some 15 lines of code.
Easily you can do if you know the Xmlns then just replace
xdoc is your xml File then,
xdoc.LoadXml(xdoc.OuterXml.Replace("xmlns=\"http://www.onvif.org/ver10/topics\"", ""));
then you can select any node
var node = xdoc.SelectNodes("RecordingConfig/JobState");

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.

Categories