Get all the xml childname - c#

I have this code and I found this on internet.
XmlDocument doc = new XmlDocument();
doc.LoadXml("<book ISBN='1-861001-57-5'>" +
"<title>Pride And Prejudice</title>" +
"<price>19.95</price>" +
"</book>");
XmlNode root = doc.FirstChild;
//Display the contents of the child nodes.
if (root.HasChildNodes)
{
for (int i = 0; i < root.ChildNodes.Count; i++)
{
//inner text contains the value of the childnode
Console.WriteLine(root.ChildNodes[i].Name);
}
}
It does work, but when I load the XML file from the disk it doesn't give output. Why?
string xmlText = File.ReadAllText("Filename");
doc.LoadXml(xmlText);

You could use Load method if you have file path.
XmlDocument doc = new XmlDocument();
doc.Load("filepath");

Try this.
XDocument doc = XDocument.Load(Server.MapPath("yourfile.xml"));//Load file from disk
var NodeNames = doc.Descendants("book").Elements().Select(x => x.Name.LocalName).ToList();
You will have to specify the path of folder if your file resides inside folder.

Related

Can't get XML node when using namespace

I looked everywhere and can't read the value of an XML node that has a namespace prefix when using the namespace manager.
XmlDocument rssXmlDoc = new XmlDocument();
rssXmlDoc.Load("https://www.kijiji.ca/rss-srp-batterie-percussion/quebec/c612l9001");
StringBuilder rssContent = new StringBuilder();
XmlNamespaceManager nsmgr = new XmlNamespaceManager(rssXmlDoc.NameTable);
nsmgr.AddNamespace("dc", #"http://schemas.microsoft.com/office/infopath/2003/myXSD/2005-08-25T08-37-41");
nsmgr.AddNamespace("g-core", #"http://schemas.microsoft.com/office/infopath/2003/myXSD");
XmlNodeList rssNodes = rssXmlDoc.SelectNodes("rss/channel/item");
// Iterate through the items in the RSS file
foreach (XmlNode rssNode in rssNodes)
{
String itemsForList = "";
XmlNode rssSubNodeTitle = rssNode.SelectSingleNode("title");
XmlNode rssSubNodePrice = rssNode.SelectSingleNode("g-core:price", nsmgr);
if (rssSubNodeTitle != null && rssSubNodeTitle.InnerText != "")
{
itemsForList = rssSubNodeTitle.InnerText;
if (rssSubNodePrice != null) { itemsForList += " (" + rssSubNodePrice.InnerText + ")"; }
}
listBox1.Items.Add(WebUtility.HtmlDecode(itemsForList));
}
The URI for the g-core namespace was wrong. It works for me when corrected to the following:
nsmgr.AddNamespace("g-core", #"http://base.google.com/ns/1.0");
When debugging these things it's helpful to save the XML to a local file and examine it in Visual Studio, Code, etc.

Can not read XML document containing ampersand symbol

I am writing a program that reads a XML file with Visual C#. I have a problem reading the Xml file, because it contains invalid XML symbols, for example '&'.
I have to read the XML but I can not modify the document. How can I modify the Xml file using C#? My code so far:
private void button1_Click(object sender, EventArgs e)
{
XmlDocument doc;
doc = new XmlDocument();
doc.Load("nuevo.xml");
XmlNodeList Xpersonas = doc.GetElementsByTagName("personas");
XmlNodeList Xlista = ((XmlElement)Xpersonas[0]).GetElementsByTagName("edad");
foreach (XmlElement nodo in Xlista)
{
string edad = nodo.GetAttribute("edad");
string nombre = nodo.InnerText;
textBox1.Text = nodo.InnerXml;
}
As #EBrown suggested, one possibility would be read the file content in a string variable and replace the & symbol with the correct representation for propert XML & and then parse the XML structure. A possible solution could look like this:
var xmlContent = File.ReadAllText(#"nuevo.xml");
XmlDocument doc;
doc = new XmlDocument();
doc.LoadXml(xmlContent.Replace("&", "&"));
XmlNodeList Xpersonas = doc.GetElementsByTagName("personas");
XmlNodeList Xlista = ((XmlElement)Xpersonas[0]).GetElementsByTagName("edad");
foreach (XmlElement nodo in Xlista)
{
string edad = nodo.GetAttribute("edad");
string nombre = nodo.InnerText;
Console.WriteLine(nodo.InnerXml.Replace("&", "&"));
}
The output is:
34 & 34
If it is ok to use LINQ2XML, then the solution is even shorter, and there is no need to write the reverse(second) replace, because LINQ2XML make this for you automatically:
var xmlContent = File.ReadAllText(#"nuevo.xml");
var xmlDocument = XDocument.Parse(xmlContent.Replace("&", "&"));
var edad = xmlDocument.Root.Element("edad").Value;
Console.WriteLine(edad);
The output is the same as above.

Incorrect parsing of Textbox in docx by OpenXML

I am reading a .docx file using OpenXML in C#. It reads everything correctly but strangely, the content of textbox is being read thrice. What could be wrong? Here is the code to read .docx:
public static string TextFromWord(String file)
{
const string wordmlNamespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
StringBuilder textBuilder = new StringBuilder();
using (WordprocessingDocument wdDoc = WordprocessingDocument.Open(file, false))
{
// Manage namespaces to perform XPath queries.
NameTable nt = new NameTable();
XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
nsManager.AddNamespace("w", wordmlNamespace);
// Get the document part from the package.
// Load the XML in the document part into an XmlDocument instance.
XmlDocument xdoc = new XmlDocument(nt);
xdoc.Load(wdDoc.MainDocumentPart.GetStream());
XmlNodeList paragraphNodes = xdoc.SelectNodes("//w:p", nsManager);
foreach (XmlNode paragraphNode in paragraphNodes)
{
XmlNodeList textNodes = paragraphNode.SelectNodes(".//w:t", nsManager);
foreach (System.Xml.XmlNode textNode in textNodes)
{
textBuilder.Append(textNode.InnerText);
}
textBuilder.Append(Environment.NewLine);
}
}
return textBuilder.ToString();
}
The part of file I am talking about is:
The result is: I read it in a test application like this:
What's wrong here?

How to load multiple files(*.xml) via XmlDocument C#

I wanted to load multiple .xml files in C#. Currently, I am able to load only 1 .xml file.
But not able to find out how will be able to load multiple files .
My code:
XmlDocument doc = new XmlDocument();
string path = #"path of *.xml file"; //
doc.Load(path);
Your code doesn't have to bee too big, you just need to store all the paths in some collection, then you have to apply the same operation to each XML file.
string newValue = "1234";
XmlDocument doc;
var paths = new[] { "config1.xml", "config2.xml" };
paths.ToList().ForEach(path =>
{
doc = new XmlDocument();
doc.Load(path);
// process the document
var nm = new XmlNamespaceManager(doc.NameTable);
var a = doc.SelectSingleNode("//SomeKeyValue", nm);
a.InnerText = newValue;
// save the file
doc.Save(path);
});

Inserting data at specific position in XML

I want to read an XML file and match tag </contrib-group> and write a string after this tag
string Final = File.ReadAllText(Npath);
string Oxml = path + "\\" + Oword + ".abs.xml";
if (File.Exists(Oxml))
{
StreamReader xml = new StreamReader(Oxml,Encoding.UTF8);
string xmltag = xml.ReadToEnd();
//File.OpenWrite(Oxml);
xml.Close();
StreamWriter write = new StreamWriter(Oxml, true, Encoding.UTF8);
Match tag = Regex.Match(xmltag, #"</contrib-group>");
if (tag.Success == true)
{
write.WriteLine(Environment.NewLine);
write.Write(Final);
}
}
So I need to write the string Final to the XML file called Oxml after the matched XML tag </contrib-group>
If you are willing to save the new content as a valid XML file which you can work with, you should use the XML classes for that approach, this should look like this (untested):
XmlDocument doc = new XmlDocument();
doc.Load("YourFile.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList elemList = root.GetElementsByTagName("contrib-group");
for (int i=0; i < elemList.Count; i++)
{
XmlNode xnode = elemList[i];
XmlNode xnodeParent = xnode.ParentNode;
XMLNode newNode = doc.CreateNode(XmlNodeType.Element, "NodeName", "");
newNode.InnerText = "ContentInsideTheNode";
xnodeParent.InsertAfter(newNode, xnode);
}
doc.Save("YourFile.xml");
If you only need to replace the string for other purposes than saving it where having a valid XML is not an issue you can just handle it as a string and use the String.Replace (String, String) Method
string searchedTag = #"</contrib-group>";
string tagAndNewContent = #"</contrib-group>" + newContent;
string fileContentString = File.ReadAllText("YourFile.xml");
string ouput = fileContentString.Replace(searchedTag, tagAndNewContent);

Categories