How to change update the element value in XML with C#? - c#

I have a xml file and wanted to update and save the value of target load with C# code. My code is as below which is trying to xml shown below -
var fileName = textBox1.Text;
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.Load(fileName);
xmlDoc.SelectSingleNode("factoryTest/targetLoad").InnerText = "80";
xmlDoc.Save(fileName);
<?xml version="1.0" encoding="utf-8"?>
<factoryTest xmlns="urn:gcpm">
<targetLoad>90</targetLoad>
<isAccepted>true</isAccepted>
<isCertified>true</isCertified>
<isAtRatingConditions>true</isAtRatingConditions>
<supervisorName>Eric Larson</supervisorName>
</factoryTest>

I have resolved this issue.
XDocument xdoc = XDocument.Load(tFileName);
xdoc.Elements("{urn:gcpm}factoryTest").Elements("{urn:gcpm}targetLoad").FirstOrDefault().Value = textBox2.Text;
xdoc.Save(tFileName);

Related

Value of xml node returning as null

I have an xml document that I am loading in my asp .net application. It is structured like this
-<Event>
<Event_Name>Special Name</Event_Name>
<Event_Date>5/27/2016 12:00:00 AM</Event_Date>
<Event_Description>Event Description</Event_Description>
</Event>
I am loading it in my code behind like this
XmlDocument doc = new XmlDocument();
string path = Server.MapPath("~/NewsXMLNews.xml");
doc.Load(path);
This loads properly. The problem is, I want to set the Event_Name as the text of a label on my aspx page. I do this using the following code
string nameOfEvent = doc.SelectSingleNode("Event_Name").ToString();
eventName.Text = nameOfEvent;
The problem is that nameOfEvent is coming back as null, so I get a nullReferenceException
I'm not exactly what I'm doing incorrectly here.
Since you already checked the path is correct and the document is properly loaded I think you just need to change the following line:
string nameOfEvent = doc.SelectSingleNode("/Event/Event_Name").InnerText;
Edit: I check with following steps that xml loading process works:
I remove the minus before in described xml file and saved
following lines as c:\temp\Event.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Event>
<Event_Name>Special Name</Event_Name>
<Event_Date>5/27/2016 12:00:00 AM</Event_Date>
<Event_Description>Event Description</Event_Description>
</Event>
Then I succeeded in running:
public Form1()
{
InitializeComponent();
XmlDocument doc = new XmlDocument();
string path = "c:\\temp\\Event.xml";
doc.Load(path);
string nameOfEvent = doc.SelectSingleNode("/Event/Event_Name").InnerText;
eventName.Text = nameOfEvent;
}
In my window I see Label named eventName text is Special Name
as expected.
This should work:
XmlNode nameOfEvent = doc.SelectSingleNode("/Event/Event_Name");
string text = nameOfEvent.InnerText;
eventName.Text = text;

SqlXml removes XML header when comes from string

I'm developing a web app with C# and MVC4. Currently I'm working in converting string vars to SqlXml files. I have a XML file with this structure:
<?xml version="1.0" encoding="utf-8"?>
<cfdi:Comprobante xsi:schemaLocation="http://www.sat.gob.mx/cfd/3 http://www.sat.gob.mx/sitio_internet/cfd/3/cfdv32.xsd http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/TimbreFiscalDigital/TimbreFiscalDigital.xsd" xmlns:tfd="http://www.sat.gob.mx/TimbreFiscalDigital" version="3.2" xmlns:cfdi="http://www.sat.gob.mx/cfd/3" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</cfdi:Comprobante>
I'm converting the above file to string successfully and then I'm usign the following code that converts a string to a SqlXML.
cfdiDocumento.CFDIXML = Serializar.XMLToSqlXml(comprobante);
Where cfdiDocumento.CFDIXML is a SqlXml var, Serializar.XMLToSqlXml(comprobante) method receives a string and executes the following code:
public static SqlXml XMLToSqlXml(string xmlString)
{
SqlXml sqlXmlFiltro = null;
if (xmlString != null)
{
StringReader sr = new StringReader(xmlString);
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Auto;
XmlReader reader0 = XmlReader.Create(sr, settings);
sqlXmlFiltro = new SqlXml(reader0);
}
return sqlXmlFiltro;
}
When the code finishes successfully, the file is correct but is removing the xml header
<?xml version="1.0" encoding="utf-8"?>
The question is: How do I preserve the xml header when convierting to SqlXml var?
If you cannot change the type of your SqlXml attribute, you could try converting the SqlXml to xml document to append xml declaration and get the outer xml:
public string SqlXmlToString(SqlXml sqlXml)
{
XmlDocument doc = new XmlDocument();
doc.Load(sqlXml.CreateReader());
// Create XML declaration with your encoding.
XmlDeclaration xmldecl;
xmldecl = doc.CreateXmlDeclaration("1.0", null, null);
xmldecl.Encoding = "UTF-8";
// Add to the document the created declaration
XmlElement root = doc.DocumentElement;
doc.InsertBefore(xmldecl, root);
return doc.OuterXml;
}
Hope this is helpfully

XML document processing cant load file

I am writing an application where i need to pull information out of a XML Document.
My XML document is stored in my projects bin/ Debug file.
I cant get it working.
XML document named informationData:
<xml>
<information>
<name >stian</name>
<surname>Kruger</surname>
<tel>0825514302</tel>
<photo>1234JLJ.jpg</photo>
</information>
</xml>
my call code:
private void btnReadXML_Click(object sender, EventArgs e)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("informationData.xml");
XmlNodeList dataNodes = xmlDoc.SelectNodes("/information");
foreach (XmlNode node in dataNodes)
{
Name = node.SelectSingleNode("name").InnerText;
Surname = node.SelectSingleNode("surname").InnerText;
TelNumber = Convert.ToInt32(node.SelectSingleNode("tel").InnerText);
}
}
Your XPath selector is wrong. Replace:
XmlNodeList dataNodes = xmlDoc.SelectNodes("/information");
with:
XmlNodeList dataNodes = xmlDoc.SelectNodes("//information");
or with:
XmlNodeList dataNodes = xmlDoc.DocumentElement.SelectNodes("information");
Also make sure that the XML file is present in the same folder as the running executable (you said bin/Debug/informationData.xml). If the XML file is part of your Visual Studio project you could select it and in the properties set Copy to Output Directory to Copy if newer. This way VS will automatically copy the XML file to this output folder everytime you compile the project.
You can use this code
<?xml version="1.0" encoding="utf-8" ?>
<information>
<name >stian</name>
<surname>Kruger</surname>
<tel>0825514302</tel>
<photo>1234JLJ.jpg</photo>
</information>
var xmlDoc = XDocument.Load("informationData.xml");
var name = xmlDoc.Element("name").Value;
var surname = xmlDoc.Element("surname").Value;
var telNumber = Convert.ToInt32(xmlDoc.Element("tel").Value);
add <?xml version="1.0" encoding="utf-8"?> as first line in XML file

Preserve xml formatting using XmlDocument

I am using XmlDocument to work with xml
How do I save my "XmlDocument" with my current formatting?
Current formatting:
<?xml version="1.0" encoding="utf-8"?>
<root>
<element></element>
</root>
Code:
XmlDocument testDoc = new XmlDocument();
testDoc.Load(#"C:\Test.xml");
**(do reading/writing using only XmlDocument methods)**
testDoc.Save(#"C:\Test.xml");
There is a similar topic:
XmlDocument class is removing formatting, c#, .NET
The accepted answer is PreserveWhiteSpace = true, which in reality removes all whitespaces instead of preserving them.
Example:
Code:
XmlDocument testDoc = new XmlDocument();
testDoc.Load(#"C:\Test.xml");
testDoc.PreserveWhitespace = true;
testDoc.Save(#"C:\Test.xml");
Result:
<?xml version="1.0" encoding="utf-8"?><root><element></element></root>
Setting PreserveWhitespace to true works for me - but you've got to do it before loading so that the whitespace doesn't get thrown away at load time:
using System;
using System.Xml;
class Test
{
static void Main()
{
XmlDocument testDoc = new XmlDocument();
testDoc.PreserveWhitespace = true;
testDoc.Load("Test.xml");
testDoc.Save("Output.xml");
}
}
I've just tried that, and the whitespace was preserved.
Umm. I'm seeing whitespace being preserved when using PreserveWhiteSpace=true. Perhaps it was false when you loaded?
var xmlStr = #"<?xml version=""1.0"" encoding=""utf-8""?>
<root>
<element></element>
</root>";
var xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(xmlStr);
xmlDoc.Save(Console.Out);
Shows:
<?xml version="1.0" encoding="utf-16"?>
<root>
<element></element>
</root>
use preservewhitespace before you load. It will keep formatting same
like above
var xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.LoadXml(xmlStr);
if you will use it after loading. it will kill white spaces in between

Create new XmlDocument from existing XmlDocument Data in Asp.Net

I have an XmlDocument that is from a webservice, and I want to use a subset of the xml to populate a Gridview control. Unfortunately, it contains extra data that I don't need. So I want to create a new XmlDocument from a subset of the existing xml document.
protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xmlDoc = Object.ReturnsXmlDocument;
XmlDocument xmlDocResults = ??? //<results><result></result></results>
}
Basically, I want to create a new XmlDocument with the as the root element. Below is a shortened example of the original xml doc:
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<query_time>.12</query_time>
<number_results>3</number_results>
<results>
<result><id>1</id></result>
<result><id>2</id></result>
<result><id>3</id> </result>
</results>
</xml>
Anthony's code helped point me in the right direction, but this is what actually worked for me.
XmlDocument xmlResults = new XmlDocument();
XmlDeclaration xmlDec = xmlResults.CreateXmlDeclaration("1.0", "utf-8", null);
XmlElement rootNode = xmlResults.CreateElement("results");
xmlResults.InsertBefore(xmlDec, xmlResults.DocumentElement);
xmlResults.AppendChild(rootNode);
XmlNode node = xmlDoc.GetElementsByTagName("results")[0];
xmlResults.GetElementsByTagName("results")[0].InnerXml = node.InnerXml.ToString();
What you need is ImportNode:-
XmlDocument xmlDoc = Object.ReturnsXmlDocument;
XmlDocument xmlResults = new XmlDocument();
xmlResults.AppendNode(xmlResults.ImportNode(xmlDoc.SelectSingleNode("/xml/results"));
Untested, but this should be pretty darn close:
XPathDocument original = new XPathDocument("original.xml");
XPathNavigator navigator = original.CreateNavigator();
navigator.MoveToChild("results", "");
XmlWriter results = XmlWriter.Create("results.xml");
navigator.WriteSubtree(results);
results.Close();
And then you can do whatever you need to with the XmlWriter - I'm not sure if you're trying to create the results XmlDocument on disk or not.

Categories

Resources