Trying to create dynamic XML file and save the data to it, however i am able to save the last entry and not all the entries. Any thoughts?
To generate XML file with needed nodes:
GenerateXML()
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode albums = doc.CreateElement("albums");
doc.AppendChild(albums);
XmlNode album = doc.CreateElement("album");
albums.AppendChild(album);
XmlNode title = doc.CreateElement("title");
albums.AppendChild(title);
doc.Save(System.Windows.Forms.Application.StartupPath + "\\albums.xml");
The output from button click gives me either 10 records or 100 records or some number of records:
//album is a class returned by web service
if (Elements.Count > 0)
{
string path = System.Windows.Forms.Application.StartupPath + "\\albums.xml";
//Read the file stream in read mode
FileStream READER = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
System.Xml.XmlDocument albumSpecs = new System.Xml.XmlDocument();
albumSpecs.Load(READER);
FileStream WRITER = null;
GenerateXML();
//Create a FileStream for writing
WRITER = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//albums");
for (int i = 0; i < ResultsList.Items.Count - 1; i++)
{
album = (Album)ResultsList.Items[i];
foreach (XmlNode node in nodes)
{
node["title"].InnerText = album.Title;
}
}
//Write the data to the filestream
doc.Save(WRITER);
}
I get the last entry data in the XML and not all the entries returned.
<?xml version="1.0" encoding="UTF-8"?>
<albums>
<album />
<title>She will be loved</title>
</albums>
How do i build run time XML based on the # of entries returned?
First load already saved xml into XmlDocument and then add new elements into it ...
GenerateXML()
string xmlFilePath = Path.Combine(System.Windows.Forms.Application.StartupPath, "albums.xml");
XmlDocument doc = new XmlDocument();
XmlNode albums = null;
if (!File.Exists(xmlFilePath))
{
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
albums = doc.CreateElement("albums");
doc.AppendChild(albums);
}
else
{
doc.Load(xmlFilePath);
albums = doc.ChildNodes[1];
}
XmlNode album = doc.CreateElement("album");
albums.AppendChild(album);
XmlNode albumName = doc.CreateElement("name");
album.AppendChild(albumName);
XmlNode title = doc.CreateElement("title");
album.AppendChild(title);
doc.Save(xmlFilePath);
Try adding elements to your XML document ?
for (int i = 0; i < ResultsList.Items.Count - 1; i++)
{
album = (Album)ResultsList.Items[i];
foreach (XmlNode node in nodes)
{
node["title"].InnerText = album.Title;
}
}
This sample of code isnt doing much, because you only have one element to iterate on ...
Edit :
I imagine you want to do something like this :
for(int i = 0; i < ResultsList.Items.count -1; i++)
{
XmlNode child = doc.createElement("Title");
doc.AppendChild .....
}
doc.save;
Related
I have a simple function which will simply change and read the value.
void ParseXml(string XmlFile)
{
string totalval = "";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(new StringReader(XmlFile));
string xmlPathPattern = "//name";
XmlNodeList mynodelist = xmldoc.SelectNodes(xmlPathPattern);
foreach (XmlNode node in mynodelist)
{
XmlNode name = node.FirstChild;
name.Value = "asd";//here I am trying to change value
totalval = totalval + "Name=" + name.OuterXml + "\n";
}
xmldoc.Save(XmlFile);
print(totalval);
}
This is my .xml file.
<name>John</name>
I can successfully read the value but it is not changing the value from .xml file.After running the program it must be like this
<name>asd</name> .
Where is my mistake ?
Obviously, the XMLFile is not a file path, it is xml string. So, you should define a valid path to save it.
xmldoc.Save("samplefile.xml");
or if you want to set the XmlFile variable with modified xml;
XmlFile = xmldoc.OuterXml;
Complete codes look like;
void ParseXml(string XmlFile)
{
string totalval = "";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(new StringReader(XmlFile));
string xmlPathPattern = "//name";
XmlNodeList mynodelist = xmldoc.SelectNodes(xmlPathPattern);
foreach (XmlNode node in mynodelist)
{
XmlNode name = node.FirstChild;
name.Value = "asd";//here I am trying to change value
totalval = totalval + "Name=" + name.OuterXml + "\n";
}
//XmlFile = xmldoc.OuterXml;
xmldoc.Save("samplefile.xml");
print(totalval);
}
If I'm not wrong - you need to fire disposable to save stream. Easiest way - wrap with using
void ParseXml(string XmlFile)
{
string totalval = "";
using(XmlDocument xmldoc = new XmlDocument())
{
xmldoc.Load(new StringReader(XmlFile));
string xmlPathPattern = "//name";
XmlNodeList mynodelist = xmldoc.SelectNodes(xmlPathPattern);
foreach (XmlNode node in mynodelist)
{
XmlNode name = node.FirstChild;
name.Value = "asd";//here I am trying to change value
totalval = totalval + "Name=" + name.OuterXml + "\n";
}
xmldoc.Save(XmlFile);
print(totalval);
}
}
I try to load my XML file into tree-view, and I fail to do so. Only I get element name. I want my tree-view load with XML attributes. My question is how to get XML attributes to load my tree-views?
Kind Regards,
MAIN FORM
This is my form that Initialize the XML file.
public Form1()
{
InitializeComponent();
// Create an instance of the open file dialog box.
// This is test purpose only. In production xml files will come from SQL Database.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
// Set filter options and filter index.
openFileDialog1.Title = "Please Choose XML File";
openFileDialog1.Filter = "XML Files (.xml)|*.xml|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;// varsayılan olarak jpg uzantıları göster
openFileDialog1.Multiselect = false;
// Call the ShowDialog method to show the dialog box.
openFileDialog1.ShowDialog();
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNode xmlnode;
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
xmldoc.Load(fs);
xmlnode = xmldoc.ChildNodes[1];
treeView1.Nodes.Clear();
treeView1.Nodes.Add(new TreeNode(xmldoc.DocumentElement.Name));
TreeNode tNode;
tNode = treeView1.Nodes[0];
AddNode(xmlnode, tNode);
}
XML LOAD
This is my xml load sub.
// XML NODE: ADD
private void AddNode(XmlNode inXmlNode, TreeNode inTreeNode)
{
XmlNode xNode;
TreeNode tNode;
XmlNodeList nodeList;
int i = 0;
if (inXmlNode.HasChildNodes)
{
nodeList = inXmlNode.ChildNodes;
for (i = 0; i <= nodeList.Count - 1; i++)
{
xNode = inXmlNode.ChildNodes[i];
inTreeNode.Nodes.Add(new TreeNode(xNode.Name));
tNode = inTreeNode.Nodes[i];
AddNode(xNode, tNode);
}
}
else
{
inTreeNode.Text = inXmlNode.InnerText.ToString();
}
}
This is XML Code:
<?xml version="1.0" encoding="utf-8"?>
<Menu>
<AgencyType id="1" name="WATER" Active="Y">
<AgencyCode id="1" name="FRESH" Active="Y">
<TypeOfBills id="1" name="INTKON" Active="Y">
<PaymentType id="1" name="AA" Active="Y"></PaymentType>
<PaymentType id="2" name="BB" Active="N" /></PaymentType>
<PaymentType id="3" name="CC" Active="N"></PaymentType>
</TypeOfBills>
</AgencyCode>
</AgencyType>
</Menu>
ORGINAL XML FILE
This is my "XML Notepad 2007" application that I build my xml files.
TREEVIEW XML LOAD
This is how my treeview shown on the form, after when I load my xml data.
Try something like this
else
{
inTreeNode.Text = inXmlNode.InnerText.ToString();
//add new code here
XmlNode inXmlNode = null;
XmlAttributeCollection attributes = null;
inXmlNode.Attributes.CopyTo(atttributes);
foreach(XmlAttribute attribute in attributes)
{
string name = attribute.Name;
string value = attribute.Value;
}
}
Thank you. I made it. Here it is. I used "XElement" and it loads very fast.
Main:
using System.Xml.Linq;
public Form1()
{
InitializeComponent();
// Create an instance of the open file dialog box.
// This is test purpose only. In production xml files will come from SQL Database.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
// Set filter options and filter index.
openFileDialog1.Title = "Please Choose XML File";
openFileDialog1.Filter = "XML Files (.xml)|*.xml|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = false;
// Call the ShowDialog method to show the dialog box.
openFileDialog1.ShowDialog();
FileStream fs = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
var data = XElement.Load(openFileDialog1.FileName);
TreeNode treeNode = treeView1.Nodes.Add("Menu");
LoadElements(data, treeNode);
//Clear ListBox items
ListBoxMain.Items.Clear();
//Load ListBox First time
foreach (TreeNode n in treeView1.Nodes)
{
ListBoxMain.Items.Add(n.Text);
}
}
LOAD ELEMENTS
private void LoadElements(XElement xElem, TreeNode treeNode)
{
foreach (XElement element in xElem.Elements())
{
if (element.HasElements)
{
if (element.FirstAttribute != null)
{
TreeNode tempNode = treeNode.Nodes.Add(element.FirstAttribute.Value + "." + element.Attribute("name").Value);
LoadElements(element, tempNode);
}
else
{
LoadElements(element, treeNode);
}
}
else
treeNode.Nodes.Add(element.FirstAttribute.Value + "." + element.Attribute("name").Value);
}
}
I have two XML files that I need to compare for differences, the XML is very simple:
File 1:
<?xml version="1.0" encoding="utf-8"?>
<Feeds zone="my zone">
<Feed name="attribDump.json">ac1f07edc491a3d237cdfb1a17fc4551</Feed>
<Feed name="focus_GroupsKV.txt">0f9e0a14a4ffce6ff5065b6e088c1f84</Feed>
<Feed name="NAM_FORMATTED.csv">9e875496cdb072b5e54318d51295fdba</Feed>
<Feed name="BNP\activityTitles.txt">2d27c0f19b71b4b411bcb00011d3f8b0</Feed>
</Feeds>
and File 2:
<?xml version="1.0" encoding="utf-8"?>
<FeedsRequest version="1">
<Feeds zone="my zone">
<Feed name="attribDump.json">ac1f07edc491a3d237cdfb1a17fc4551</Feed>
<Feed name="focus_GroupsKV.txt">0f9e0a14a4ffce6ff5065b6e088c1f84</Feed>
<Feed name="BNP\activityTitles.txt">e54c5b851ee3ff3f43b10d24f2316431</Feed>
</Feeds>
</FeedsRequest>
File 1 is an inventory list of files on our file share and File 2 is used by a disconnected device that will need to be refreshed from File 1. The checks I need to make are 1) make sure all of the feeds in File 1 are in File 2 and 2) make sure any feeds that are found have the same hashCode(the long character string). Once the checks have been completed, I need to create a response file that has a list of all of the feeds and then an attribute on each one that designates ok (file was found and matched), missing (file wasn't found), or updated (file was found but it was an older version).
So basically the result file would look as such:
<?xml version="1.0" encoding="utf-8"?>
<FeedsResponse version="1">
<Feeds zone="my zone">
<Feed name="attribDump.json" status="ok">ac1f07edc491a3d237cdfb1a17fc4551</Feed>
<Feed name="focus_GroupsKV.txt" status="ok">0f9e0a14a4ffce6ff5065b6e088c1f84</Feed>
<Feed name="NAM_FORMATTED.csv" status="missing">afd2c620053ed4f85ab02b4cc5f7a2b2</Feed>
<Feed name="BNP\activityTitles.txt" status="updated">90805b851ee3ff3f43b10d24f2316431</Feed>
What I'm doing currently is looping through all of the files in File 1, then checking them against File 2 for differences. Where I'm stuck, been a while since I've worked with XML, is how to build out the response document.
FileInfo feedList = new FileInfo(_feedList);
FileInfo feedRequest = new FileInfo(_feedRequest);
// Load the documents
XmlDocument feedListXmlDoc = new XmlDocument();
feedListXmlDoc.Load(_feedList);
// Load the documents
XmlDocument feedRequestXmlDoc = new XmlDocument();
feedRequestXmlDoc.Load(_feedRequest);
//create response doc
XmlDocument feedResponseXmlDoc = new XmlDocument();
// Define a single node
XmlNode feedListNode;
XmlNode feedRequestNode;
// Get the root Xml element
XmlElement feedListRoot = feedListXmlDoc.DocumentElement;
XmlElement feedRequestRoot = feedRequestXmlDoc.DocumentElement;
// Get a list of all player names
XmlNodeList feedListXml = feedListRoot.GetElementsByTagName("Feed");
XmlNodeList feedRequestXml = feedRequestRoot.GetElementsByTagName("Feed");
// Create an XmlWriterSettings object with the correct options.
XmlWriter writer = null;
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = (" ");
settings.OmitXmlDeclaration = false;
// Create the XmlWriter object and write some content.
writer = XmlWriter.Create(_resultPath, settings);
writer.WriteStartElement("FeedsDiff");
// The compare algorithm
bool feedMatch = false;
int j = 0;
try
{
// loop through list of current feeds
for (int i = 0; i < feedListXml.Count; i++)
{
feedListNode = feedListXml.Item(i);
string feedListName = feedListNode.Attributes["name"].Value.ToString();
string feedListHash = feedListXml.Item(i).InnerText.ToString();
//check feed request list for a match
while (j < feedRequestXml.Count && feedMatch == false)
{
feedRequestNode = feedRequestXml.Item(j);
string feedRequestName = feedRequestNode.Attributes["name"].Value.ToString();
//checks to see if feed names match
if (feedListName == feedRequestName)
{
feedMatch = true;
string feedRequestHash = feedRequestXml.Item(j).InnerText.ToString();
//since we found the node, we can remove it from the request list
XmlNode node = feedRequestNode.ParentNode;
node.RemoveChild(feedRequestNode);
//checks to see if hash codes match
if (feedListHash == feedRequestHash)
{
//if name and code match, move to the next one
feedMatch = true;
//add 'status="ok"' attribute to the node
//feedResponseXmlDoc.ImportNode(feedRequestNode,false);
Debug.WriteLine(feedListName + " name and hash match");
j = 0;
}
else
{
feedMatch = true;
//feed has been updated since last device sync
//need to add status='update' attribute and append file to response
Debug.WriteLine(feedListName + " name matched but hash did not");
}
}
else
{
//names didn't match
//add status="missing" to the node
j++;
}
}
feedMatch = false;
}
// end Xml document
writer.WriteEndElement();
writer.Flush();
}
finally
{
if (writer != null)
writer.Close();
}
Right now I'm trying to instantiate the response doc before the loop and then just add the elements as they are found but I'm having a hard time finding a concise way to do it. Any help is appreciated.
Take a look at differ, from my open-source project CodeBlocks over on CodePlex, it was designed for situations such as this one. It is also available on Nuget as "differ"
I figured it out:
public void CompareXml(string _feedList, string _feedRequest, string _resultPath)
{
FileInfo feedList = new FileInfo(_feedList);
FileInfo feedRequest = new FileInfo(_feedRequest);
// Load the documents
XmlDocument feedListXmlDoc = new XmlDocument();
feedListXmlDoc.Load(_feedList);
// Load the documents
XmlDocument feedRequestXmlDoc = new XmlDocument();
feedRequestXmlDoc.Load(_feedRequest);
// Define a single node
XmlNode feedListNode;
XmlNode feedRequestNode;
// Get the root Xml element
XmlElement feedListRoot = feedListXmlDoc.DocumentElement;
XmlElement feedRequestRoot = feedRequestXmlDoc.DocumentElement;
// Get a list of feeds for the stored list and the request
XmlNodeList feedListXml = feedListRoot.GetElementsByTagName("Feed");
XmlNodeList feedRequestXml = feedRequestRoot.GetElementsByTagName("Feed");
bool feedLocated = false;
int j = 0;
try
{
// loop through list of current feeds
for (int i = 0; i < feedListXml.Count; i++)
{
feedListNode = feedListXml.Item(i);
//create status attribute
XmlAttribute attr = feedListXmlDoc.CreateAttribute("status");
string feedListName = feedListNode.Attributes["name"].Value.ToString();
string feedListHash = feedListXml.Item(i).InnerText.ToString();
//check feed request list for a match
while (j < feedRequestXml.Count && feedLocated == false)
{
feedRequestNode = feedRequestXml.Item(j);
string feedRequestName = feedRequestNode.Attributes["name"].Value.ToString();
//checks to see if feed names match
if (feedRequestName == feedListName)
{
string feedRequestHash = feedRequestXml.Item(j).InnerText.ToString();
//checks to see if hashCodes match
if (feedListHash == feedRequestHash)
{
//if name and code match, set status to ok
attr.Value = "ok";
Debug.WriteLine(feedListName + " name and hash match. Status: 'ok'");
}
else
{
//if hashCodes don't match, set status attribute to updated
attr.Value = "updated";
Debug.WriteLine(feedListName + " name matched but hash did not. Status: 'updated'");
}
feedListNode.Attributes.Append(attr);
feedLocated = true;
}
else
{
//names didn't match, checking to see if we're at the end of the request list
if (j + 1 == feedRequestXml.Count)
{
//file name wasn't found in the request list, set status attribute to missing
attr.Value = "missing";
feedListNode.Attributes.Append(attr);
feedLocated = true;
j = 0;
Debug.WriteLine("Reached the end of the file request list without a match. Status: 'missing'");
}
//file name wasn't located on this pass, move to next record
j++;
}
}
feedLocated = false;
}
}
finally
{
Debug.WriteLine("Result file has been written out at " + _resultPath);
}
feedListXmlDoc.Save(_resultPath);
}
I want to write XML Log File from two or more Application into LogData.xml file. while running the one application it creats the LogData.xml file correctly but at the same time both the allpication are run simulteniously and try to write the LogData.xml file it gives me an error message such as The process cannot access the file Log_Data.xml' because it is being used by another process.
I use this code
public void WriteXmlLog(string logType, string logFlag, string logModule, string logLocation, string logText, string logStackTrace)
{
if (!File.Exists(_logFilePath))
{
//File.WriteAllText(_logFilePath, "<?xml version='1.0' encoding='utf-8' standalone='yes'?>\r\n<AppXmlLogWritter></AppXmlLogWritter>");
XmlTextWriter textWritter = new XmlTextWriter(_logFilePath, null);
textWritter.WriteStartDocument();
textWritter.WriteStartElement("AppXmlLogWritter");
textWritter.WriteEndElement();
textWritter.Close();
}
XmlDocument xmlDoc = new XmlDocument();
using (FileStream fileStream = new FileStream(_logFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
string currentDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
xmlDoc.Load(fileStream);
XmlElement newelement = xmlDoc.CreateElement("LogData");
XmlElement xmlLogID = xmlDoc.CreateElement("LogID");
XmlElement xmlLogDateTime = xmlDoc.CreateElement("LogDateTime");
XmlElement xmlLogType = xmlDoc.CreateElement("LogType");
XmlElement xmlLogFlag = xmlDoc.CreateElement("LogFlag");
XmlElement xmlLogApplication = xmlDoc.CreateElement("LogApplication");
XmlElement xmlLogModule = xmlDoc.CreateElement("LogModule");
XmlElement xmlLogLocation = xmlDoc.CreateElement("LogLocation");
XmlElement xmlLogText = xmlDoc.CreateElement("LogText");
XmlElement xmlLogStackTrace = xmlDoc.CreateElement("LogStackTrace");
xmlLogID.InnerText = _logIDPrefix + currentDateTime + randomNumber;
xmlLogDateTime.InnerText = currentDateTime;
xmlLogType.InnerText = ((LogTypes)Convert.ToInt32(logType)).ToString();
xmlLogFlag.InnerText = logFlag;
xmlLogApplication.InnerText = _logApplication;
xmlLogModule.InnerText = logModule;
xmlLogLocation.InnerText = logLocation;
xmlLogText.InnerText = logText;
xmlLogStackTrace.InnerText = logStackTrace;
newelement.AppendChild(xmlLogID);
newelement.AppendChild(xmlLogDateTime);
newelement.AppendChild(xmlLogType);
newelement.AppendChild(xmlLogFlag);
newelement.AppendChild(xmlLogApplication);
newelement.AppendChild(xmlLogModule);
newelement.AppendChild(xmlLogLocation);
newelement.AppendChild(xmlLogText);
xmlDoc.DocumentElement.AppendChild(newelement);
//}
//finally
//{
// objMutex.ReleaseMutex();
//}
}
xmlDoc.Save(_logFilePath);
}
I want to achive this without Threading
Perhaps try implementing logging with NLog in both applications and set as the target the same xml.
Thank you very much for reading my question.
and this is my xml file. (for node Songs, many childNodes named Song)
<?xml version="1.0" encoding="utf-8" ?>
<xmlData>
<version>1.0</version>
<Songs>
<Song>
<artist>mic</artist>
<track>2</track>
<column>happy</column>
<date>14</date>
</Song>
<Song>
<artist>cool</artist>
<track>2</track>
<column>work</column>
<date>4</date>
</Song>
</Songs>
</xmlData>
reading xml, i use the following code:
XmlDocument doc = new XmlDocument();
doc.Load(xmlFilePath);
XmlNode versionNode = doc.SelectSingleNode(#"/xmlData/version");
Console.WriteLine(versionNode.Name + ":\t" + versionNode.InnerText);
XmlNode SongsNode = doc.SelectSingleNode(#"/xmlData/Songs");
Console.WriteLine(SongsNode.Name + "\n");
XmlDocument docSub = new XmlDocument();
docSub.LoadXml(SongsNode.OuterXml);
XmlNodeList SongList = docSub.SelectNodes(#"/Songs/Song");
if (SongList != null)
{
foreach (XmlNode SongNode in SongList)
{
XmlNode artistDetail = SongNode.SelectSingleNode("artist");
Console.WriteLine(artistDetail.Name + "\t: " + artistDetail.InnerText);
XmlNode trackDetail = SongNode.SelectSingleNode("track");
Console.WriteLine(trackDetail.Name + "\t: " + trackDetail.InnerText);
XmlNode columnDetail = SongNode.SelectSingleNode("column");
Console.WriteLine(columnDetail.Name + "\t: " + columnDetail.InnerText);
XmlNode dateDetail = SongNode.SelectSingleNode("date");
Console.WriteLine(dateDetail.Name + "\t: " + dateDetail.InnerText + "\n");
}
}
it seems working.
but how can i write the change to xml file?
maybe, i will change some childNode in Song, and may delete the whole chindNode by artist keyword.
is it possible such as this function
bool DeleteSongByArtist(string sArtist);
bool ChangeNodeInSong(string sArtist, string sNodeName, string value);
because the "Reading solution is "XmlDucoment", so it is better if "changing solution" by using "XmlDocument"
but, if you have better idea to read and change the xml file, please give me the sample code... and please don't write a name of solution such as "Ling to xml"...acutally, i do many testes, but failed.
Welcome to Stackoverflow!
You can change the nodes simply by setting a new .Value or in your case .InnerText.
Sample
// change the node
trackDetail.InnerText = "NewValue"
// save the document
doc.Save(xmlFilePath);
More Information
How To: Modify an Existing Xml File
MSDN - XmlDocument.Save Method
You need to use an XmlWriter. The easiest way to do it would be something like this...
using(XmlWriter writer = new XmlWriter(textWriter))
{
doc.WriteTo(writer);
}
Where textWriter is your initialized Text Writer.
Actually, forget that... the easiest way is to call...
doc.Save(xmlFilePath);
To delete an artist by artist name add the following method:
bool DeleteSongByArtist(XmlDocument doc, string artistName)
{
XmlNodeList SongList = doc.SelectNodes(#"/Songs/Song");
if (SongList != null)
{
for (int i = SongList.Count - 1; i >= 0; i--)
{
if (SongList[i]["artist"].InnerText == artistName && SongList[i].ParentNode != null)
{
SongList[i].ParentNode.RemoveChild(SongList[i]);
}
}
}
}
You probably want to clean it up a bit more to be more resilient. When you call it, change your initial code to be like this. Don't create the subDocument as you want to work with the entire XmlDocument.
XmlDocument doc = new XmlDocument();
doc.Load(xmlFilePath);
XmlNode versionNode = doc.SelectSingleNode(#"/xmlData/version");
Console.WriteLine(versionNode.Name + ":\t" + versionNode.InnerText);
XmlNode SongsNode = doc.SelectSingleNode(#"/xmlData/Songs");
Console.WriteLine(SongsNode.Name + "\n");
XmlNodeList SongList = doc.SelectNodes(#"/Songs/Song");
if (SongList != null)
{
foreach (XmlNode SongNode in SongList)
{
XmlNode artistDetail = SongNode.SelectSingleNode("artist");
Console.WriteLine(artistDetail.Name + "\t: " + artistDetail.InnerText);
XmlNode trackDetail = SongNode.SelectSingleNode("track");
Console.WriteLine(trackDetail.Name + "\t: " + trackDetail.InnerText);
XmlNode columnDetail = SongNode.SelectSingleNode("column");
Console.WriteLine(columnDetail.Name + "\t: " + columnDetail.InnerText);
XmlNode dateDetail = SongNode.SelectSingleNode("date");
Console.WriteLine(dateDetail.Name + "\t: " + dateDetail.InnerText + "\n");
}
}
You aren't able to save your changes because you made changes to an entirely new document!
You likely meant to do the following:
XmlNode SongsNode = doc.SelectSingleNode(#"/xmlData/Songs");
Console.WriteLine(SongsNode.Name + "\n");
// Don't make a new XmlDocument here! Use your existing one
XmlNodeList SongList = SongsNode.SelectNodes(#"/Song");
At this point SongList is still living inside doc. Now when you call:
doc.Save(xmlFilePath);
Your changes will be saved as you intended.
If you're looking to delete nodes that match certain criteria:
// Use XPath to find the matching node
XmlNode song = SongsNode.SelectSingleNode(#"/Song[artist='" + artist + "']");
// Remove it from its Parent
SongsNode.RemoveChild(song);
If you're looking to add a new node:
// Create the new nodes using doc
XmlNode newSong = doc.CreateElement("Song");
XmlNode artist = doc.CreateElement("artist");
artist.InnerText = "Hello";
// Begin the painstaking process of creation/appending
newSong.AppendChild(artist);
// rinse...repeat...
// Finally add the new song to the SongsNode
SongsNode.AppendChild(newSong);
You could do
XmlNodeList SongList = doc.SelectNodes(#"//Songs/Song");
The // tells it to select the Songs node anywhere in document. This is better than
doc.SelectNodes(#"/document/level1/music/Songs")
Note that the above statement is oviously not for your xml, but to prove a point about //
Using // removes the need for your docSub document and SongsNode element.
To add then delete a song, just use the following
XmlDocument doc = new XmlDocument();
XmlElement ea = doc.SelectSingleNode("//songs");
XmlElement el = doc.CreateElement("song");
XmlElement er;
ea.AppendChild(el);
//doing my work with ea
//you could use innerxml.
el.InnerXml = "<artist>Judas Priest</artist><track>7</track><column>good</column><date>1</date>";
//or you can treat each node as above
er = doc.CreateElement("Name");
el.AppendChild(er);
er.InnerText = "The Ripper";
//but you don't nead this song any more?
ea.RemoveChild(el);
//so it's gone.
And thats all there is to it.
please don't write a name of solution such as "Ling to xml"...acutally, i do many testes, but failed.
Still I think, this is a very good time to start to use Linq2Xml. If you don't like it, just ignore.
XDocument xDoc = XDocument.Load(new StringReader(xml));
//Load Songs
var songs = xDoc.Descendants("Song")
.Select(s => new
{
Artist = s.Element("artist").Value,
Track = s.Element("track").Value,
Column = s.Element("column").Value,
Date = s.Element("date").Value,
})
.ToArray();
//Delete Songs
string songByArtist="mic";
xDoc.Descendants("Song")
.Where(s => s.Element("artist").Value == songByArtist)
.Remove();
string newXml = xDoc.ToString();