I have following sample xml file
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<IResponse xmlns:xsi="http://www.w3.org/2001/XMLScheminstance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Language>en</Language>
<Code>Approved</Code>
<Message> Approved</Message>
<Info xsi:type="Info">
<Number>11</Number>
<ExpiryDate year="10" month="8" />
<StartDate year="7" month="8" />
<currency="GBP">36.00</currency>
<ACode>096392</ACode>
</IResponse>
How to display the nodes and child elemants in treeview control and values in the list view?
public void Deserialize()
{
XmlReader reader = XmlReader.Create(this.filePath);
XmlSerializer serializer = new XmlSerializer(typeof(Response));
if (serializer.CanDeserialize(reader))
{
Response obj = serializer.Deserialize(reader) as Response;
// obj consists of xml file nodes and i want to display this in treeview
// control and values in between them as list view .
}
else
{
iccTransactionResponseBindingSource.DataSource = null;
}
}
Maybe this MS KB document? http://support.microsoft.com/kb/317597
Related
i write some UWP app. There i want to save/Update/Delete in a XML List. My XML List Looks like:
<?xml version="1.0" encoding="utf-8"?>
<rootnode>
<Kunde Name="Testkunde" />
<Kunde Name="Testkunde2" />
</rootnode>
If i want to remove a item with this code
StorageFolder folder = await StorageFolder.GetFolderFromPathAsync(#"C:\Users\IT\source\repos\App3\App3");
StorageFile file = await folder.GetFileAsync("Kundenliste.xml");
using (IRandomAccessStream writeStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
Stream s = writeStream.AsStreamForWrite();
XDocument doc = XDocument.Load(s);
var q = from node in doc.Descendants("Kunde")
let attr = node.Attribute("Name")
where attr != null && attr.Value == "Testkunde"
select node;
q.ToList().ForEach(x => x.Remove());
doc.Save(s);
}
This happens
<?xml version="1.0" encoding="utf-8"?>
<rootnode>
<Kunde Name="Testkunde" />
<Kunde Name="Testkunde2" />
</rootnode><?xml version="1.0" encoding="utf-8"?>
<rootnode>
<Kunde Name="Testkunde2" />
</rootnode>
anyone can help me?
Just set
s.Position = 0;
s.SetLength(0);
after
Stream s = writeStream.AsStreamForWrite();
XDocument doc = XDocument.Load(s);
and it will works
I have the following XML that I am trying to "load" into an XmlDocument object:Link to XML File
I have the following method piece of code to load the XML document:
public XmlDocument getDirections()
{
XmlTextReader xmlReader;
XmlDocument xmlResponse = new XmlDocument();
StringBuilder xmlResponseString = new StringBuilder();
xmlReader = new XmlTextReader(getRequestURL()); //getRequestURL gives the URL for XML doucument
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
xmlResponseString.Append(xmlReader.ReadInnerXml());
}
}
xmlResponse.LoadXml(xmlResponseString.ToString());
return xmlResponse;
}
When I run the code, I get the following error:
An unhandled exception of type 'System.Xml.XmlException' occurred in System.Xml.dll
Additional information: There are multiple root elements. Line 3, position 3.
I figured this happens because the XML document have multiple route objects but I don't know how to fix it. Any help would be appreciated !
The line where it says:
Additional information: There are multiple root elements. Line 3, position 3.
This is your clue.
Properly formatted XML will have 1 root element.
Ex.
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
See for a further explanation: http://www.w3schools.com/xml/xml_syntax.asp
What's the point of doing it that way? Use the built in functionality for getting Xml from a Url:
var str = #"https://maps.googleapis.com/maps/api/directions/xml?origin=Jamaica,%20NY%2011418&destination=Hunter%20College%20Park%20Avenue%20New%20York&mode=&alternatives=true&key=AIzaSyB8G9omVUu6a_OQCrRM-QItdwk-Hxq__mg";
var doc = new XmlDocument();
doc.Load(str);
//or
var xdoc = XDocument.Load(str);
I would look into Linq to Xml (XDocument) over XmlDocument. It's a lot easier to work with.
You can use following snippet to load xml.
public XmlDocument getDirections()
{
XmlTextReader xmlReader;
XmlDocument xmlResponse = new XmlDocument();
StringBuilder xmlResponseString = new StringBuilder();
HttpWebRequest request =HttpWebRequest.Create(getRequestURL());
using(HttpWebResponse response = (HttpWebResponse) request.GetResponse())
{
if (response.StatusCode == HttpStatusCode.OK)
{
using (var responseStream = response.GetResponseStream())
{
xmlResponse.Load(responseStream);
}
}
}
xmlResponse.LoadXml(xmlResponseString.ToString());
return xmlResponse;
}
I came across a similar incident when trying to read an Xml using the XmlReader.
My code:
using (XmlReader reader = XmlReader.Create(new StringReader(filesContent)))
{
while (reader.Read()) //<--- This is where the exception was caught
{
// Do stuff here
}
}
The exception caught:
An unhandled exception of type 'System.Xml.XmlException' occurred in
System.Xml.dll
Additional information: There are multiple root elements. Line X,
position Y.
Note: The information regarding the location of the line and position which were provided in the exception were not the actual line or the position in the xml file content where my additional root was, making this a bit misleading.
A properly formatted xml file should contain only ONE root. As such:
<?xml version="1.0" encoding="UTF-8" ?>
<root1>
<child1>
<subchild1>.....</subchild1>
</child1>
</root1>
In my case the exception was being thrown because my xml file contained 2 roots.
<?xml version="1.0" encoding="UTF-8" ?>
<root1>
<child1>
<subchild1>.....</subchild1>
</child1>
</root1>
<root2>
<child1>
<subchild1>.....</subchild1>
<subchild2>.....</subchild2>
</child1>
<child2>
<subchild1>.....</subchild1>
</child2>
</root2>
This could easily be fixed by adding some 'parentroot' to the file, making the 2 roots nest under the new parent root as such
<?xml version="1.0" encoding="UTF-8" ?>
<parnetroot>
<root1>
<child>
<subchild>.....</subchild>
</child>
</root1>
<root2>
<child1>
<subchild1>.....</subchild1>
<subchild2>.....</subchild2>
</child1>
<child2>
<subchild1>.....</subchild1>
</child2>
</root2>
</parnetroot>
I have an xml file which I need to modify and write it back to an outputfile.
The problem is that the result outputfile contains an extra attribute 'standalone' in the root declartion which does not exist in the original inputfile.
Is there any way how I can prevent from XmlDocument adding this attribute ?
The code I have tried:
//read input xml
XmlDocument xDoc = new XmlDocument();
xDoc.Load(originalFile);
//do some stuff
//....
//write back to output
using(XmlTextWriter xml2 = new XmlTextWriter(outputFile, Encoding.UTF8) { Formatting = Formatting.Indented })
{
xDoc.CreateXmlDeclaration("1.0", null, "");
xDoc.Save(xml2);
}
inputfile contains this:
<?xml version="1.0" encoding="UTF-8" ?>
...
output.xml contains this:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
...
The standalone parameter should be null or String.empty.
xDoc.CreateXmlDeclaration("1.0", null, null);
Also CreateXmlDecleration just creates a declaration object. You still need to add it to the document, like this:
XmlDeclaration xDecl = xDoc.CreateXmlDeclaration("1.0", null, null);
if (xDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
xDoc.ReplaceChild(xDecl, xDoc.FirstChild);
else
xDoc.InsertBefore(xDecl, xDoc.DocumentElement);
I'm trying to find existing content within an XML file and change it by making use of the SelectSingleNode command. However, all I get is a NullReferenceException. Maybe I'm just not getting how the file path works with this particular command, but I've tried many variants I've found online but to no avail. Could anyone help me figure out what I'm doing wrong?
Here's the script.
public void saveStuff()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"Worlds\WorldData.xml"); //loads the file just fine
XmlNode node = xmlDoc.SelectSingleNode("//World[#ID='002']/Name"); //node = null
node.Value = "New Name"; //NullReferenceException was unhandled
xmlDoc.Save(#"Worlds\example.xml");
}
And here's a sample of my XML file.
<?xml version="1.0" encoding="utf-8" ?>
<XnaContent>
<World ID="001">
<Name>
TinyWorld
</Name>
<Size>
4x4
</Size>
<Tiles>
000,000,000,001,
000,000,000,001,
001,001,004,001,
001,001,001,001,
</Tiles>
</World>
<World ID="002">
<Name>
MicroWorld
</Name>
<Size>
2x2
</Size>
<Tiles>
000,000,
001,001,
</Tiles>
</World>
</XnaContent>
Instead:
public void saveStuff()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"Worlds\WorldData.xml");
XmlElement root = xmlDoc.DocumentElement;
XmlNode node = root.SelectSingleNode("//World[#ID='002']/Name");
node.Value = "New Name";
xmlDoc.Save(#"Worlds\example.xml");
}
You were selecting using the // xpath, but at that moment, no context. That syntax is relative to the current node.
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