//I would like to get some advice on how to replace the node value of a element in XML using XMLElement or XElement. Right now I'm trying it with XMLElement but the compiler gives me only errors or the XML replace the whole document insted of selected node. I have a XML/XSD sample that I need to fill with data and create like 500 XML a day but I cant insert the data into the right elements. I expect that I can replace / insert data into the element value. Like I want to change the City text value. I have a table with content and based on the filled data I need to add it into specific XML elements and save. As for now every sample code I found and some I covered up did give compile errors / null reference object( at assigning InnerText) or deleted all the elements and added just one line with my text value.
Te code below gives me ''Object reference not set to an instance of an object.' ' at .InnerText. Actually the declatarion of SelectSingleNode("ID") return me also a null.
-<Receiver>
-<ID>
<RNumber>9999999999</RNumber>
<Name>ABC AGD sp. z o. o.</Name>
</ID>
-<Address>
-<AddressSpec>
<Country>PL</Country>
<Street>Kwiatowa</Street>
<HouseNum>1</HouseNum>
<City>Warszawa</City>
</AddressSpec>
</Address>
<Email>[email protected]</Email>
<Phone>667444555</Phone>
</ID>
-</Receiver>
using System.IO;
using System.Net;
using System.Xml;
using System.Xml.Linq;
class ReplaceXMLData
{
public static void Main(Args _args)
{
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
doc.Load(//path/sample.xml);
System.Xml.XmlElement root = doc.DocumentElement;
System.Xml.XmlElement Street = doc.SelectSingleNode("Street");
Street.innertext = "random";
doc.AppendChild(root);
doc.Save(path);
info("Details added Successfully");
}}
CodePudding user response:
Here is solution using Xml Linq (XDocument). You need to use Decendants with FirstOrDefault
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
namespace ConsoleApplication15
{
class Program
{
const string FILENAME = @"c:\temp\test.xml";
static void Main(string[] args)
{
XDocument doc = XDocument.Load(FILENAME);
XElement id = doc.Descendants("ID").FirstOrDefault();
}
}
}