Insert line in xml doc - c#

I wanna insert in second line :
<?mso-application progid="Excel.Sheet"?>
but I'm started to think that it is impossible.
Here is my base code:
XmlDocument doc = new XmlDocument();
XmlReader reader = cmd.ExecuteXmlReader();
doc.LoadXml("<results></results>");
XmlNode newNode = doc.ReadNode(reader);
while (newNode != null)
{
doc.DocumentElement.AppendChild(newNode);
newNode = doc.ReadNode(reader);
}

Just Try like this
XmlNode XNode = doc.CreateProcessingInstruction("mso-application ", "progid=\"Excel.Sheet\"");
doc.AppendChild(XNode);

<?mso-application progid="Excel.Sheet"?> is a processing instruction not an element so you need to use the CreateProcessingInstruction Method

Related

Can't figure out how to read xml data in Visual Studio C#

I'm not sure how to read out the data from a XML file.
The XML file looks like this:
<?xml version="1.0" encoding="utf-8"?>
<Lijsten>
<Lijst>
<Titel>Discipline</Titel>
<Waardes>Elektro</Waardes>
<Waardes>Mechanisch</Waardes>
<Waardes>Civiel</Waardes>
<Waardes>Proces</Waardes>
</Lijst>
<Lijst>
<Titel>Soort</Titel>
<Waardes>Tekening</Waardes>
<Waardes>Tekst doc</Waardes>
<Waardes>Afbeelding</Waardes>
</Lijst>
<Lijst>
<Titel>Afdruk</Titel>
<Waardes>Landscape</Waardes>
<Waardes>Portrait</Waardes>
</Lijst>
<Lijst>
<Titel>Kleur</Titel>
<Waardes>Kleur</Waardes>
<Waardes>Zwart</Waardes>
</Lijst>
<Lijst>
<Titel>Kader</Titel>
<Waardes>Aanwezig</Waardes>
<Waardes>Niet aanwezig</Waardes>
</Lijst>
</Lijsten>
I'm trying to create a radio-button menu for every "Lijst".
What I've got so far(not much):
XmlTextReader reader = new XmlTextReader("iniFile.xml");
while (reader.Read())
{
while (reader.ReadToFollowing("Lijst"))
{
while (reader.ReadToFollowing("Titel"))
{
}
}
}
If you don't want to read using XElement, you can use XmlDocument and XPath
Take a look at this example, to get all titles:
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"C:\temp\inifile.xml");
XmlNodeList nodes = xdoc.SelectNodes("//Titel");
foreach (XmlNode node in nodes)
{
Console.WriteLine(node.InnerText);
}
or, to get all Lijst nodes and then iterate through them to get title and warde values
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"C:\temp\inifile.xml");
XmlNodeList nodes = xdoc.SelectNodes("//Lijst");
foreach (XmlNode node in nodes)
{
Console.WriteLine("this is List with title: " + node["Titel"].InnerText);
Console.WriteLine("it contains wardes: " + node["Titel"].InnerText);
XmlNodeList wardeNodes = node.SelectNodes("Waardes");
foreach (XmlNode wNode in wardeNodes)
{
Console.WriteLine(" - " + wNode.InnerText);
}
}
With XElement class and LinqToXML:
XElement xml = XElement.Parse(xml);
var buttons = xml.Element("Lijsten")
.Elements()
.Select(p => new { Titel = p.Element("Titel").Value })
.ToArray();

Read Array in XML in C#

I'm trying to read arrays in an XML, but my code does not return results
XML :
<ArrayOfProductoModel
xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/WebApi.Models">
<ProductoModel>
<descripcion>descripcion 1</descripcion>
<fecha_registro>2016-03-01</fecha_registro>
<id_producto>1</id_producto>
<id_proveedor>1</id_proveedor>
<nombre_producto>producto 1</nombre_producto>
<precio>200</precio>
</ProductoModel>
<ProductoModel>
<descripcion>descripcion 3</descripcion>
<fecha_registro>2016-08-02</fecha_registro>
<id_producto>3</id_producto>
<id_proveedor>3</id_proveedor>
<nombre_producto>producto 3</nombre_producto>
<precio>500</precio>
</ProductoModel>
</ArrayOfProductoModel>
Code :
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(content);
XmlNodeList nodelist = xDoc.SelectNodes("ArrayOfProductoModel/ProductoModel");
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("descripcion").InnerText);
}
As I can read the array?
The problem is the imported namespace. You can ignore the namespace as explained here:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(content);
XmlNodeList nodelist = xDoc.DocumentElement.SelectNodes("*[local-name()='ProductoModel']");
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("*[local-name()='descripcion']").InnerText);
}
Alternatively you can use an XmlNamespaceManager as explained here:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(content);
XmlNamespaceManager manager = new XmlNamespaceManager(xDoc.NameTable);
manager.AddNamespace("MYNS", "http://schemas.datacontract.org/2004/07/WebApi.Models");
XmlNodeList nodelist = xDoc.DocumentElement.SelectNodes("MYNS:ProductoModel", manager);
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("MYNS:descripcion", manager).InnerText);
}
Another solution is to use Linq to XML
var xml = #"<ArrayOfProductoModel
xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""
xmlns=""http://schemas.datacontract.org/2004/07/WebApi.Models"">
<ProductoModel>
<descripcion>descripcion 1</descripcion>
<fecha_registro>2016-03-01</fecha_registro>
<id_producto>1</id_producto>
<id_proveedor>1</id_proveedor>
<nombre_producto>producto 1</nombre_producto>
<precio>200</precio>
</ProductoModel>
<ProductoModel>
<descripcion>descripcion 3</descripcion>
<fecha_registro>2016-08-02</fecha_registro>
<id_producto>3</id_producto>
<id_proveedor>3</id_proveedor>
<nombre_producto>producto 3</nombre_producto>
<precio>500</precio>
</ProductoModel>
</ArrayOfProductoModel>";
var xDoc = XDocument.Parse(xml);
var ns = xDoc.Root.Name.Namespace;
var nodelist = xDoc.Element(ns + "ArrayOfProductoModel").Elements(ns + "ProductoModel");
foreach (var node in nodelist)
{
MessageBox.Show(node.Element(ns + "descripcion").Value);
}
Don't forget to put namespace in front of local name.
At first, I think problem in
xDoc.LoadXml(content);
You try:
xDoc.Load(filePathXml);
Second, I think problem in
XmlNodeList nodelist = xDoc.SelectNodes("ArrayOfProductoModel/ProductoModel");
foreach (XmlNode node in nodelist)
{
MessageBox.Show(node.SelectSingleNode("descripcion").InnerText);
}
You try:
XmlNode rootNode = doc.SelectSingleNode(#"/ArrayOfProductoModel");
var listProductModel = rootNode.SelectNodes(#"ProductoModel");
foreach (XmlNode node in listProductModel)
{
MessageBox.Show(node.SelectSingleNode("descripcion").InnerText);
}

Query for unique id with XDocument

I have the following XML name Sample.xml which I am trying to query uniqueID with XDocument:
<Request>
<Person xmlns="http://CompanyName.AppName.version1" uniqueID="3221">
<AccountNo>83838</AccountNo>
<FirstName>Tom</FirstName>
<LastName>Jackson</LastName>
</Person>
<Person xmlns="http://CompanyName.AppName.version1" uniqueID="21132">
<AccountNo>789875</AccountNo>
<FirstName>Chris</FirstName>
<LastName>Smith</LastName>
</Person>
</Request>
How do i write code to extract uniqueID of all persons.
You can use LINQ to XML to retrieve the unique ID from your XML document.
string xml = "<Request><Person xmlns='http://CompanyName.AppName.version1' uniqueID='3221'><AccountNo>83838</AccountNo><FirstName>Tom</FirstName><LastName>Jackson</LastName></Person><Person xmlns='http://CompanyName.AppName.version1' uniqueID='21132'><AccountNo>789875</AccountNo><FirstName>Chris</FirstName><LastName>Smith</LastName></Person></Request>";
XDocument doc = XDocument.Parse(xml);
XNamespace ns = "http://CompanyName.AppName.version1";
var uniqueIDs = doc.Descendants(ns + "Person")
.Select(p => p.Attribute("uniqueID").Value)
.ToList();
Try below code With XmlDocument in place
string xml = "<Request><Person xmlns='http://CompanyName.AppName.version1' uniqueID='3221'><AccountNo>83838</AccountNo><FirstName>Tom</FirstName><LastName>Jackson</LastName></Person><Person xmlns='http://CompanyName.AppName.version1' uniqueID='21132'><AccountNo>789875</AccountNo><FirstName>Chris</FirstName><LastName>Smith</LastName></Person></Request>";
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
XmlNodeList nodeList = xmlDoc.GetElementsByTagName("Person");
foreach (XmlNode node in nodeList)
{
Console.WriteLine(node.Attributes["uniqueID"].Value);
}
You can get the Unique ID by:
string xml="Your XML String";
XmlTextReader reader = new XmlTextReader(new System.IO.StringReader(xml));
XmlDocument doc = new XmlDocument();
XmlNode node = doc.ReadNode(reader);
foreach (XmlNode chldNode in node.ChildNodes)
{
if (chldNode.HasChildNodes)
{
foreach (XmlNode item in node.ChildNodes)
{
string uniqueID = chldNode.Attributes["uniqueID"].Value;
Response.Write(employeeName + "<br />");
}
}
}

get node value from string xml

I have this string XML
string innerXml = #"<detail><WCFFaultExcepcion xmlns=""http://schemas.datacontract.org/2004/07/CIEL.DigiturnoMega.Entidades"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><ErrorId>b7e9d385-9118-4297-baca-db9ab00f3856</ErrorId><Message>Índice fuera de los límites de la matriz.</Message></WCFFaultExcepcion></detail>";
This is the stringXML
<detail>
<WCFFaultExcepcion xmlns="http://schemas.datacontract.org/2004/07/CIEL.DigiturnoMega.Entidades" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ErrorId>b7e9d385-9118-4297-baca-db9ab00f3856</ErrorId>
<Message>Índice fuera de los límites de la matriz.</Message>
</WCFFaultExcepcion>
</detail>
What I want is to get the value of the detail Tag, I’m trying with this example but all return null o cero count, could you help me?
private static void Example()
{
string innerXml = #"<detail><WCFFaultExcepcion xmlns=""http://schemas.datacontract.org/2004/07/CIEL.DigiturnoMega.Entidades"" xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><ErrorId>b7e9d385-9118-4297-baca-db9ab00f3856</ErrorId><Message>Índice fuera de los límites de la matriz.</Message></WCFFaultExcepcion></detail>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(innerXml);
XmlNode node = (XmlNode)doc.DocumentElement;
XmlNode optionalNode = node.SelectSingleNode("/detail/WCFFaultExcepcion");
XmlNode optionalNode1 = node.SelectSingleNode("detail/WCFFaultExcepcion");
XmlNode optionalNode2 = node.SelectSingleNode("/detail/WCFFaultExcepcion/ErrorId");
XmlNode optionalNode3 = node.SelectSingleNode("detail/WCFFaultExcepcion/ErrorId");
XmlElement optional = doc.SelectSingleNode(#"/detail/WCFFaultExcepcion/ErrorId") as XmlElement;
XmlElement optiona2 = doc.SelectSingleNode(#"detail/WCFFaultExcepcion/ErrorId") as XmlElement;
XmlNode xNode = doc.DocumentElement.SelectNodes("ErrorId")[0];
XmlNodeList xnList = doc.SelectNodes("/detail/WCFFaultExcepcion");
XmlNodeList xnList1 = doc.SelectNodes("detail/WCFFaultExcepcion");
XmlNodeList xnList2 = doc.SelectNodes("/detail/WCFFaultExcepcion/ErrorId");
XmlNodeList xnList3 = doc.SelectNodes("detail/WCFFaultExcepcion/ErrorId");
}
I think this might be the solution for you:
XmlDocument doc = new XmlDocument();
doc.LoadXml(innerXml);
XmlNodeList ErrorIdTags = doc.GetElementsByTagName("ErrorId");
if(ErrorIdTags.Count <= 1)
{
// The tag could not be fond
}
else
{
// The tag could be found!
string ErrorId = ErrorIdTags[0].InnerText;
}
Try using Linq to Xml (http://msdn.microsoft.com/en-us/library/bb387098%28v=VS.100%29.aspx) - the code will be really elegant.
The first try XmlNode node = (XmlNode)doc.DocumentElement; should work and should contain children. Try XmlNode firstChildNode = node.FirstChild; ... this will get you the first child, and won't be empty/null.
But when using xpath, you will get into problems because of the defined namespace. You will have to create a new namespace in doc, and assign http://schemas.datacontract.org/2004/07/CIEL.DigiturnoMega.Entidades a shorthand (eg. sh ) ... then later in your xpath you can like go doc.SelectSingleNode(#"/detail/sh:WCFFaultExcepcion/sh:ErrorId")

Deleting XML using a selected Xpath and a for loop

I currently have the following code:
XPathNodeIterator theNodes = theNav.Select(theXPath.ToString());
while (theNodes.MoveNext())
{
//some attempts i though were close
//theNodes.RemoveChild(theNodes.Current.OuterXml);
//theNodes.Current.DeleteSelf();
}
I have set xpath to what I want to return in xml and I want to delete everything that is looped. I have tried a few ways of deleting the information but it does't like my syntax. I found an example on Microsoft support: http://support.microsoft.com/kb/317666 but I would like to use this while instead of a for each.
Any comments or questions are appreciated.
Why not to use XDocument?
var xmlText = "<Elements><Element1 /><Element2 /></Elements>";
var document = XDocument.Parse(xmlText);
var element = document.XPathSelectElement("Elements/Element1");
element.Remove();
var result = document.ToString();
result will be <Elements><Element2 /></Elements>.
Or:
var document = XDocument.Load(fileName);
var element = document.XPathSelectElement("Elements/Element1");
element.Remove();
document.Savel(fileName);
[Edit] For .NET 2, you can use XmlDocument:
XmlDocument document = new XmlDocument();
document.Load(fileName);
XmlNode node = document.SelectSingleNode("Elements/Element1");
node.ParentNode.RemoveChild(node);
document.Save(fileName);
[EDIT]
If you need to remove all child elements and attributes:
XmlNode node = document.SelectSingleNode("Elements");
node.RemoveAll();
If you need to keep attributes, but delete elements:
XmlNode node = document.SelectSingleNode("Elements");
foreach (XmlNode childNode in node.ChildNodes)
node.RemoveChild(childNode);
string nodeXPath = "your x path";
XmlDocument document = new XmlDocument();
document.Load(/*your file path*/);
XmlNode node = document.SelectSingleNode(nodeXPath);
node.RemoveAll();
XmlNode parentnode = node.ParentNode;
parentnode.RemoveChild(node);
document.Save("File Path");
You can use XmlDocument:
string nodeXPath = "your x path";
XmlDocument document = new XmlDocument();
document.Load(/*your file path*/);//or document.LoadXml(...
XmlNode node = document.SelectSingleNode(nodeXPath);
if (node.HasChildNodes)
{
//note that you can use node.RemoveAll(); it will remove all child nodes, but it will also remove all node' attributes.
for (int childNodeIndex = 0; childNodeIndex < node.ChildNodes.Count; childNodeIndex++)
{
node.RemoveChild(node.ChildNodes[childNodeIndex]);
}
}
document.Save("your file path"));

Categories

Resources