Xml delete node by elements value - c#

Here is xml file:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Data>
<PageInfo>
<ID>0</ID>
<NUM>5</NUM>
<URL>er.php</URL>
</PageInfo>
<PageInfo>
<ID>1</ID>
<NUM> 12345</NUM>
<URL>/out/out.ViewFolder.php</URL>
</PageInfo>
</Data>
I have tried alot of ways (for a week now) to delete certain node (PageInfo) by element (ID,NUM,URL) in this xml file.
There are few approaches I have tried:
1st approach:
XmlDocument docc = new XmlDocument();
docc.LoadXml(AppDomain.CurrentDomain.BaseDirectory + "/WebData.xml");
XmlNode nodee = docc.SelectSingleNode("/Data/PageInfo/ID[2]");
nodee.RemoveAll();
2nd approach:
XmlDocument document = new XmlDocument();
document.Load(AppDomain.CurrentDomain.BaseDirectory + "/WebData.xml");
XmlNodeList nodes = document.DocumentElement.SelectNodes("/Data/PageInfo");
string ID, NUM, URL;
foreach (XmlNode node in nodes)
{
ID = node.SelectSingleNode("ID").InnerText;
NUM = node.SelectSingleNode("NUM").InnerText;
URL = node.SelectSingleNode("URL").InnerText;
node.RemoveAll();
Console.WriteLine(ID + " " + NUM + " " + URL + "\n");
}
1st solution does not trigger and exception but nothing happens, 2nd solution throws an exception: Data at the root level is invalid.
How one would be able to delete nodes by elements value in an xml file? (LINQ is fine)
Disclaimer: all solutions I have found on StackOverflow does not work for my certain case.

Based on the ID, please try this solution :
First approach
string xml = AppDomain.CurrentDomain.BaseDirectory + "/WebData.xml";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(xml);
XmlNode t = xmlDoc.SelectSingleNode("/Data/PageInfo[ID='0']");
t.ParentNode.RemoveChild(t);
xmlDoc.Save(xml);
Second approach : Linq
XDocument xmlDoc = XDocument.Load(xml);
var pageInfo = (from xml2 in xmlDoc.Descendants("PageInfo")
where xml2.Element("ID").Value == "0"
|| xml2.Element("NUM").Value == "5"
|| xml2.Element("URL").Value == "er.php"
select xml2).FirstOrDefault();
pageInfo.Remove();
xmlDoc.Save(xml);
// output
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<Data>
<PageInfo>
<ID>1</ID>
<NUM> 12345</NUM>
<URL>/out/out.ViewFolder.php</URL>
</PageInfo>
</Data>

As <Data> is an array so you can deserialize it in a classData which has List<PageInfo> so you can update your data accordingly and then serialize it back in your file.
Example:
XmlArray("Data")]
public class Data
{
[XmlArrayItem("PageInfo")]
public List<PageInfo> pageInfos = new List<PageInfo>();
}
public class PageInfo
{
public int ID;
public int NUM;
public string URL;
}
Now you can apply queries on your list and then deserialize your Data class back to file. See This Link for Serializing guide.

Related

Reading XML file results in index out of range exception

Using C# I have an XML file like
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account>
<name>Jani</name>
</Account>
</root>
and I also have a function to read the name node as:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("lib//user.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
label1.Text = name.ToString();
but I am getting index out of range error as:
Why is this happening?
node = xmlDoc.DocumentElement;
string name = node.Attributes[0].Value;
node is your root node. Which looks like this:
<root>
How many attributes does it have? None, as it turns out. An attribute in XML is one of these bar="baz" things:
<foo bar="baz">
node.Attributes[0] refers to the first attribute. There is no first attribute, there's no second attribute -- you didn't use attributes in this XML at all. Hence, that's out of range. There's no first item in an empty collection.
What you want is an element named name, which is farther down inside your XML tree.
Probably this:
var node = xmlDoc.DocumentElement.SelectSingleNode("/root/Account/name");
And then you'll want to look at node.InnerText to get "Jani" out of it.
You are trying to read node.Attributes[0].Value but there is no attribtues in your sample XML file. Not sure of the exact syntax but it should probably be closer to node.Value
As mentioned by other answers, your current XML does not have attributes.
private void DoIt()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
//string name = node.Attributes[0].Value;
string name = node["Account"].InnerText;
}
If your XML did have attributes
<?xml version="1.0" encoding="utf-8"?>
<root>
<Account name="Jani" />
</root>
Then you could do this:
private void DoItAgain()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"M:\StackOverflowQuestionsAndAnswers\38924171\38924171\data2.xml");
XmlNode node;
node = xmlDoc.DocumentElement;
string name = node["Account"].Attributes[0].Value;
}

How to get the values of all the elements in an XML into an array?

For example :
I have the following XML,
<?xml version="1.0" encoding="utf-8"?>
<TEST>
<Name>TESTRUN</Name>
<SyncByte>ff</SyncByte>
<SOM>53</SOM>
<PDADD>7e</PDADD>
<LENLSB>08</LENLSB>
</Test>
I would like to get the values from the tags "SyncByte", "SOM", "PADD" and "LENLSB" into a single array. Is there an option within XML to accomplish this?
P.S. There are close to 20+ tags in the XML and not all tags contain values all the time. Hence if there is a single command to get all the values of the XML, then it would be great.
With Linq to Xml:
var xml = #"<?xml version=""1.0"" encoding=""utf-8""?>
<Test>
<Name>TESTRUN</Name>
<SyncByte>ff</SyncByte>
<SOM>53</SOM>
<PDADD>7e</PDADD>
<LENLSB>08</LENLSB>
</Test>";
var doc = XDocument.Parse(xml);
string[] values = doc.Root.Descendants().Select(x => x.Value).ToArray();
First:
your xml formate is wrong , it should be:
<?xml version="1.0" encoding="utf-8"?>
<TEST>
<Name>TESTRUN</Name>
<SyncByte>ff</SyncByte>
<SOM>53</SOM>
<PDADD>7e</PDADD>
<LENLSB>08</LENLSB>
</TEST> <!--END Tag should same as TEST -->
Then you can query them like this:
var xml=XDocument.Load("d:\\test.xml");
var list=xml.Descendants("TEST")
.Select(x=>new
{
SyncByte=x.Element("SyncByte")==null?"":x.Element("SyncByte").Value,
SOM=x.Element("SOM")==null?"":x.Element("SOM").Value,
LENLSB=x.Element("LENLSB")==null?"":x.Element("LENLSB").Value
});
You can get the child of any parent node through 'XmlElement.ChildNodes' and store it in collection.
for eg :
static int Main(string[] args)
{
string strFilename = "Input.xml";
XmlDocument xmlDoc = new XmlDocument();
if (File.Exists(strFilename))
{
xmlDoc.Load(strFilename);
XmlElement elm = xmlDoc.DocumentElement;
XmlNodeList lstVideos = elm.ChildNodes;
for (int i = 0; i < lstVideos.Count; i++)
Console.WriteLine("{0}",lstVideos[i].InnerText );
}
else
Console.WriteLine("The file {0} could not be located",
strFilename);
Console.WriteLine();
return 0;
}

XML select single node not returning anything

I have the following method that is supposed to return a string that holds the calories for a given food item in an xml menu.
public string calorieCount(int choice)
{
string calCount = "250";
XmlDocument doc = new XmlDocument();
doc.Load(path);
XmlElement root = doc.DocumentElement;
XmlNode node = doc.SelectSingleNode("/menu/item[#name='Burger']/calories");
string checker = node.Value;
MessageBox.Show(checker);//returning nothing
return checker;
}
And my XML file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<menu>
<!-- Burger -->
<item name="Burger">
<name>Burger</name>
<price>$5.99</price>
<calories>500</calories>
<description>A burger made with 100% angus beef and grilled to your liking. Served with fries</description>
<count>25</count>
</item>
Why is it returning an empty string? Is my call to SelectSingleNode incorrect?
Thank you in advance.
Use InnerText instead of Value
Replace
string checker = node.Value;
With
string checker = node.InnerText;

How to read single node value from xml file

Hi i am trying to get value from xml but it shows node null.
Here is my xml file.
<?xml version="1.0" encoding="utf-8"?>
<result xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.cfhdocmail.com/TestAPI2/Result.xsd https://www.cfhdocmail.com/TestAPI2/Result.xsd" xmlns="https://www.cfhdocmail.com/TestAPI2/Result.xsd">
<data>
<key>MailingGUID</key>
<value>0aa2b2e3-7afa-4002-ab2f-9eb4cbe33ae7</value>
</data>
<data>
<key>OrderRef</key>
<value>52186</value>
</data>
</result>
I want to get "MailingGUID" value.
Here is the code that i have tried:
private void readXML()
{
XmlDocument xml = new XmlDocument();
// You'll need to put the correct path to your xml file here
xml.Load(Server.MapPath("~/XmlFile11.xml"));
// Select a specific node
XmlNode node = xml.SelectSingleNode("result/data/value");
// Get its value
string name = node.InnerText;
}
Please tell me how i can get MailingGUID value.
Thanks
UPDATE:
I think there might be something wrong with your schemas, I removed references to them and your code worked fine. I tried this:
const string str = "<?xml version=\"1.0\" encoding=\"utf-8\"?><result><data><key>MailingGUID</key><value>0aa2b2e3-7afa-4002-ab2f-9eb4cbe33ae7</value></data><data><key>OrderRef</key><value>52186</value></data></result>";
var xml = new XmlDocument();
xml.LoadXml(str);
xml.DocumentElement.SelectSingleNode("/result/data/value").InnerText
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//Parsing of xml is done here
Document doc = builder.parse(new File("C:\\Users\\User_Name\\Documents\\My Received Files\\PDSL_ABM.xml"));
//Here we get the root element of XML and print out
doc.getDocumentElement().normalize();
System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName());
NodeList list = doc.getElementsByTagName("MailingGUID");
int totalMailingGUID =list.getLength();
System.out.println("Total no of MailingGUID : " + totalSupplierPartID);
//Traversing all the elements from the list and printing out its data
for (int i = 0; i < list.getLength(); i++) {
//Getting one node from the list.
Node childNode = list.item(i);
System.out.println("MailingGUID : " + childNode.getTextContent());
}

Looping through XML Document

My Method:
if (File.Exists( #"C:\config.xml"))
{
System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
xd.Load( #"C:\config.xml");
System.Xml.XmlElement root = xd.DocumentElement;
System.Xml.XmlNodeList nl = root.SelectNodes("/config");
foreach (System.Xml.XmlNode xnode in nl)
{
string name = xnode.Name;
string value = xnode.InnerText;
string nv = name + "|" + value;
Send(nv);
}
My Xml Doc
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<config>
<bla>D</bla>
<def>300</def>
<ttOUT>34000</ttOUT>
<num>3800</num>
<pw>help</pw>
<err>1</err>
....and so on
</config>
Now my method returns the first 2 and nothing else.
What am i doing wrong...
use the System.Xml namespace to avoid long type qualifications ie...
using System.Xml;
Then try something like this..
XmlNodeList nl = xd.SelectNodes("config");
XmlNode root = nl[0];
foreach (XmlNode xnode in root.ChildNodes)
{
string name = xnode.Name;
string value = xnode.InnerText;
string nv = name + "|" + value;
Send(nv);
}
I believe there is something wrong with your method.
a) I don't think SelectNodes should take the /config argument, rather it should take config.
b) After selecting the first (and only - XML files in .Net must have one and only one root node) root node you need to iterate through the ChildNodes of the root.
root is the <config> tag, so I don't understand how root.SelectNodes("/config") should work at all. Use root.Childnodes instead.

Categories