Adding data to an existing xml file - c#

I am using the follwing syntax to add data to already existing xml file in the following way:
XmlTextReader Reader = new XmlTextReader("ServerPaths.xml");
DataSet dsNewList = new DataSet();
dsNewList.ReadXml(Reader);
Reader.Close();
DataTable dt = dsNewList.Tables[0];
dt.Rows.Add(txtNewServerPath.Text);
dt.WriteXml("ServerPaths.xml",false);
But, i was getting error at last line as:
System.IO.IOException was unhandled
Message=The process cannot access the file 'C:\Documents and Settings\590000\my documents\visual studio 2010\Projects\EasyDeployer\EasyDeployer\bin\Debug\ServerPaths.xml' because it is being used by another process
Please help in solving this error. or is there any other way to do this?
My xml file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<ServerList>
<ServerPath>C:\\Avinash\\Dev1</ServerPath>
<ServerPath>C:\\Avinash\\Dev1</ServerPath>
</ServerList>
I just wanted to add new serverpath..

You could also try adding XmlNode's to the xml document like this:
XmlDocument xd = new XmlDocument();
xd.Load("ServerPaths.xml");
XmlNode rootNode = xd.DocumentElement;
XmlNode serverPathNode = xd.CreateElement("ServerPath");
serverPathNode.InnerText = txtNewServerPath.Text; // Your value
rootNode.AppendChild(serverPathNode);
xd.Save("ServerPaths.xml");

Related

Need Help Deserializing a Xml document in c#

I need help deserializing a XML file that i got on my machine. i have tried somthing like this.
private void button1_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataSet));
FileStream readStream = new FileStream("D:\\Europoultry\\Connection Hjælp\\CIN_Example_2.xml", FileMode.Open);
ds = (DataSet)xmlSerializer.Deserialize(readStream);
readStream.Close();
dataGridView1.DataSource = ds.Tables[0];
}
but it says there is an error.
There is an error in XML-document (2, 2) System.InvalidOperationException: der is an error in XML-document(2,2): http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader'> was not expected.
I can post the XML document if it is needed but it is a long document. Hope some of you can help.
Here is a part of the XML document
<?xml version="1.0" encoding="utf-8"?>
<sh:StandardBusinessDocument xmlns:sh="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader" xmlns:eanucc="urn:ean.ucc:2" xmlns:gdsn="urn:ean.ucc:gdsn:2" xmlns:align="urn:ean.ucc:align:2" xmlns:chemical_ingredient="urn:ean.ucc:align:chemical_ingredient:2" xmlns:food_beverage_tobacco="urn:ean.ucc:align:food_beverage_tobacco:2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader http://www.gdsregistry.org/2.8/schemas/sbdh/StandardBusinessDocumentHeader.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/CatalogueItemNotificationProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/AttributeValuePairExtensionProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/CaseLevelNonGTINLogisticsUnitExtensionProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/TradeItemExtensionSpecificsProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/ChemicalIngredientExtensionProxy.xsd urn:ean.ucc:2 http://www.gdsregistry.org/2.8/schemas/FoodAndBeverageTradeItemExtensionProxy.xsd">
<sh:StandardBusinessDocumentHeader>
<sh:HeaderVersion>1.0</sh:HeaderVersion>
<sh:Sender>
<sh:Identifier Authority="EAN.UCC">5790000011032</sh:Identifier>
</sh:Sender>
<sh:Receiver>
<sh:Identifier Authority="EAN.UCC">5790000500000</sh:Identifier>
</sh:Receiver>
<sh:DocumentIdentification>
<sh:Standard>EAN.UCC</sh:Standard>
<sh:TypeVersion>2.8</sh:TypeVersion>
<sh:InstanceIdentifier>DI-35346-34535-xt435345</sh:InstanceIdentifier>
<sh:Type>catalogueItemNotification</sh:Type>
<sh:CreationDateAndTime>2013-12-20T10:46:26+00:00</sh:CreationDateAndTime>
</sh:DocumentIdentification>
</sh:StandardBusinessDocumentHeader>
<eanucc:message>
<entityIdentification>
<uniqueCreatorIdentification>MSG-35346-34535-xt435345</uniqueCreatorIdentification>
<contentOwner>
<gln>5790000011032</gln>
</contentOwner>
</entityIdentification>
<eanucc:transaction>
<entityIdentification>
<uniqueCreatorIdentification>TRN-35346-34535-xt435345</uniqueCreatorIdentification>
<contentOwner>
<gln>5790000011032</gln>
</contentOwner>
</entityIdentification>
<command>
<eanucc:documentCommand>
<documentCommandHeader type="ADD">
<!--D8164-->
<entityIdentification>
<uniqueCreatorIdentification>CMD-35346-34535-xt435345</uniqueCreatorIdentification>
<contentOwner>
<gln>5790000011032</gln>
</contentOwner>
</entityIdentification>
</documentCommandHeader>
<documentCommandOperand>
<gdsn:catalogueItemNotification creationDateTime="2013-12-20T10:46:26+00:00" documentStatus="ORIGINAL" isReload="false">
<catalogueItem>
<catalogueItemState state="IN_PROGRESS"/>
<tradeItem>
<tradeItemUnitDescriptor>CASE</tradeItemUnitDescriptor>
<!--D8276-->
<tradeItemIdentification>
Try using xsd.exe for generating a c# class from this xml document.
There is an answer here: Generate C# class from XML
Then you can deserialize the xml document to the newly generated c# class
There are a few issues here that I can see. First, the XML you're trying to deserialize to a DataSet isn't a DataSet, so the deserialization would fail. Easiest way to do what you're trying to do is to make a set of POCOs that do represent your data, annotate them appropriately, and deserialize to those, and you can then use them as you would any other object. The exception you're getting, I believe is just that the XmlSerializer doesn't recognise your root element as being the one expected by the DataSet, or simply that it cannot correctly match the namespace. You can see more details about this here (https://msdn.microsoft.com/en-us/library/aa302290.aspx#trblshtxsd_topic5). Details of controlling XML Serialization/Deserialization via annotated POCOs can be found here (https://msdn.microsoft.com/en-us/library/2baksw0z(v=vs.110).aspx).

exception occurs while saving XML using c#

I am trying to update an existing XML file by adding a new child node using c#.
Everything is OK if I save it by new name but I want to update the same file and while doing it, got the following exception:
System.IO.IOException:Process cannot access the file... because it is
being used by another process
Here is my code: (I am trying to add a new default node)
XmlDocument doc = new XmlDocument();
string path = #"C:\Debug\default.xml";
doc.Load(path);
XmlNode NName = doc.CreateElement("default");
XmlNode SNO = doc.CreateElement("SNo");
SNO.InnerText = "2";
NName.AppendChild(SNO);
doc.DocumentElement.AppendChild(NName);
doc.Save(path);
Also XML file:
<?xml version="1.0" standalone="yes"?>
<NewDataSet>
<default>
<SNo>1</SNo>
</default>
</NewDataSet>
If you are sure the file is only being used by your process, then simply read it into a byte array, close the file, then save it again:
(I am using .net 4.0 for this sample):
XmlDocument doc = new XmlDocument();
byte[] content = File.ReadAllBytes(path);
using (var memStream = new MemoryStream(content))
{
doc.Load(memStream);
}
XmlNode NName = doc.CreateElement("default");
XmlNode SNO = doc.CreateElement("SNo");
SNO.InnerText = "2";
NName.AppendChild(SNO);
doc.DocumentElement.AppendChild(NName);
doc.Save(path);

XDocument Exception: Root element is missing

I have a simple XML file:
<?xml version="1.0" encoding="utf-8" ?>
<Config>
<NumOfBytesInRow>20</NumOfBytesInRow>
<FirstBaudRate>115200</FirstBaudRate>
<SecondBaudRate>34800</SecondBaudRate>
<DefaultPort>COM1</DefaultPort>
<NumOfTries>2</NumOfTries>
</Config>
And I'm trying to get the elements, but as soon as I'm opening the file I'm getting an exception that the root element is missing
XDocument doc = new XmlDocument();
doc.Load(path);
EDIT
I have added:
if(File.Exists("D:\\BBConfig.xml"))
before the load it found the file and still same error
For the first I find the answer of user3890766 very good: "This exception could be thrown if the method can't find the file". But nevertheless you can try this for sure:
string strXml;
try
{
using (StreamReader sr = new StreamReader("myXML.xml"))
{
strXml = sr.ReadToEnd();
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(strXml);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
This exception could be thrown if the method can't find the file. You need to check if your application can find the file at the given path, and have the authorization to read it.
To be sure, you could use a Stream, and check the Length. Then use XmlDocument.Load with this Stream.

"Root element is missing" exception given when trying to parse XML file

I'm trying to set up parsing for a test XML generated with ksoap2 in Android:
<?xml version="1.0" encoding="utf-8"?>
<v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/">
<v:Header />
<v:Body>
<v:SOAPBODY>
<v:INFO i:type="v:INFO">
<v:LAITETUNNUS i:type="d:string">EI_TUNNUSTA</v:LAITETUNNUS>
</v:INFO>
<v:TOIMINNOT i:type="v:TOIMINNOT">
<v:TOIMINTA i:type="d:string">ASETUKSET_HAKU</v:TOIMINTA>
</v:TOIMINNOT>
<v:SISALTO i:type="v:SISALTO">
<v:KUVA i:type="d:string">AGFAFDGFDGFG</v:KUVA>
<v:MITTAUS i:type="d:string">12,42,12,4,53,12</v:MITTAUS>
</v:SISALTO>
</v:SOAPBODY>
</v:Body>
</v:Envelope>
But seemingly i can't parse it in any way. The exception is always that "Root element is not found" even when it goes through XML-validators like the one at w3schools. If i'm correct the contents of the body shouldn't be an issue when the problem is with root element.
The test code for parsing i try to use in C# is:
using (StreamReader streamreader = new StreamReader(Context.Request.InputStream))
{
try
{
XDocument xmlInput = new XDocument();
streamreader.BaseStream.Position = 0;
string tmp = streamreader.ReadToEnd();
var xmlreader = XmlReader.Create(streamreader.BaseStream);
xmlInput = XDocument.Parse(tmp);
xmlInput = XDocument.Load(xmlreader);
catch (Exception e)
{ }
where the xmlInput = XDocument.Parse(tmp); does indeed parse it to a XDocument, not a navigable one, though. Then xmlInput = XDocument.Load(xmlreader); throws the exception for not having a root element. I'm completely at loss here because i managed to parse and navigate the almost same xml with XMLDocument and XDocument classes before, and i fear i made some changes i didn't notice.
Thanks in advance.
Update: Here's the string tmp as requested :
"<?xml version=\"1.0\" encoding=\"utf-8\"?><v:Envelope xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\" xmlns:c=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:v=\"http://schemas.xmlsoap.org/soap/envelope/\"><v:Header /><v:Body><v:SOAPBODY><v:INFO i:type=\"v:INFO\"><v:LAITETUNNUS i:type=\"d:string\">EI_TUNNUSTA</v:LAITETUNNUS></v:INFO><v:TOIMINNOT i:type=\"v:TOIMINNOT\"><v:TOIMINTA i:type=\"d:string\">ASETUKSET_HAKU</v:TOIMINTA></v:TOIMINNOT><v:SISALTO i:type=\"v:SISALTO\"><v:KUVA i:type=\"d:string\">AGFAFDGFDGFG</v:KUVA><v:MITTAUS i:type=\"d:string\">12,42,12,4,53,12</v:MITTAUS></v:SISALTO></v:SOAPBODY></v:Body></v:Envelope>\r\n"
Update: Even with XDocument.Load(new StreamReader(Context.Request.InputStream, Encoding.UTF8)); the parsing will fail.
I believe you've read to the end of the stream once already, you need to reset the position in the stream again. see: "Root element is missing" error but I have a root element

Can not save string / node to XML WP8

I am reading the contents of an xml file perfectly into a longlistselector with tap events attached. All working great. The file sits in the main assets folder of the project.
Now i would also like to add strings/ nodes to my simple XML, but for some reason i can't find the right syntax to save it to the file.
My xml file looks like:
<?xml version="1.0" encoding="utf-8" ?>
<phrases>
<item><name>What is your name?</name></item>
<item><name>How old are you?</name></item>
</phrases>
Now I tried the following inside of a click event of a button:
XDocument xDoc = XDocument.Load("phrases.xml");
var contactsElement = new XElement("item",
new XElement("name", "blalllllaaaallaala")));
xDoc.Add(contactsElement);
xDoc.Save("phrases.xml");
VS2013 tells me that the xDoc.Save("phrases.xml") has invalid arguments. When i read from that file i provide the same path, so i dont understand what is expected here? Please give some suggestions.
Just try out with this snippet...
// load original XML from the stream
XDocument loadedData = XDocument.Load(stream);
// create a new parent XML structure (new root) and load the original nodes
var newXml = new XDocument(new XElement("Histories"));
newXml.Root.Add(loadedData.Root);
// create the new node
var contactsElement = new XElement("item",
new XElement("name", "blalllllaaaallaala")));
NewNode.Add(contactsElement);
// add the new node
newXml.Root.Add(NewNode);
// save the stream
newXml.Save(stream);
For more have a look here too.

Categories