I'm attempting to open an XML file which is copied as content to the IsolatedStorage when I compile my app and am having some issues with it;
Data at the root level is invalid. Line 1, position 411.
I'm not entirely sure what this means and a trip to my local search engine only expanded my confusion, could anybody please tell me if I'm doing anything drastically wrong or if my data structure is bad please?
Here's my function that loads the data from the file and parses it into variables:
private void ReadData()
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists("appdata.xml"))
{
IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream("appdata.xml", FileMode.Open, store);
XDocument document;
using (XmlReader reader = XmlReader.Create(fileStream))
{
if (reader != null)
{
document = XDocument.Load(reader); // <-- Error occurs here
ListBox listBox = new ListBox();
var data = from query in document.Descendants("myData")
select new DataHolder
{
CashData = (string)query.Element("CashData"),
LandGoData = (string)query.Element("LandGoData"),
FreeParkingData = (string)query.Element("FreeParkData"),
CircuitData = (string)query.Element("FullCircuitData"),
AuctionData = (string)query.Element("AuctionData")
};
listBox.ItemsSource = data;
StartCashRule.Text = (string)listBox.FindName("myData");
}
}
fileStream.Close();
}
}
}
And here's my xml document:
<?xml version="1.0" encoding="utf-8" ?>
<RootPath>
<CashData>Value1</CashData>
<LandGoData>Value2</LandGoData>
<FreeParkData>Value3</FreeParkData>
<FullCircuitData>Value4</FullCircuitData>
<AuctionData>Value5</AuctionData>
</RootPath>
Related
I have a service that is processing data and exporting out xml files for another service, which usually handles small amount of data(About 5 files a minute) but sometimes a large chunk of data is dumped and it may handle needing to create 100 files all at once.
The service runs mostly fine but it occasionally runs into an error:
The process cannot access the file 'C:\File.xml' because it is being used by another process.
This is strange because the file should be created, written, and closed all in one shot, so I don't know what could be giving this problem. The issue seems to happen more frequently under heavy load, but still occurs regularly under light loads as well. Naturally this never shows up while debugging or I probably would have fixed this by now.
Here is the function that actually writes the file:
public bool WriteDocument(Object Data)
{
XmlDocument X = new XmlDocument();
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(null, "Schema.xsd");
X.Schemas = schemaSet;
if (!Directory.Exists("OutputDirectory"))
{
Directory.CreateDirectory("OutputDirectory");
}
string File = Path.Combine("OutputDirectory", #"File" + ".xml");
XmlSerializer Encoder = new XmlSerializer(typeof(Object));
//Do stuff to data object to prepare for output
using (MemoryStream buffer = new MemoryStream())
{
Encoder.Serialize(buffer, Data);
buffer.Position = 0;
X.Load(buffer);
X.Validate((sender, e) =>
{
if (e.Severity == XmlSeverityType.Error)
{
result = false;
}
else
{
result = true;
}
});
}
if (result)
{
while (System.IO.File.Exists(File))
{
File = MakeUniqueName(File);
}
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
using (XmlWriter Writer = XmlWriter.Create(File, settings))
{
X.WriteTo(Writer);
Writer.Close();
}
}
return result;
}
I am wanting to convert a large amount of xml data near 600mb where i wont no its headers or root nodes I did try the following code but its complaining it does not no its root nodes. What is the most effiecent way of processiing a large file.
using (FileStream fs = new FileStream(#"C:\Projects\csvExport\csvExport\csvExport\bin\VLFLBNM7.xml", FileMode.Open))
{
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "ReportDetails";
// xRoot.Namespace = "http://www.cpandl.com";
xRoot.IsNullable = true;
XmlSerializer serializer = new XmlSerializer(typeof(Sequence[]),xRoot);
var data = (Sequence[])serializer.Deserialize(fs);
List<string> list = new List<string>();
foreach (var item in data)
{
List<string> ss = new List<string>();
foreach (var point in item.SourcePath) ss.Add(point.X + "," + point.Y);
list.Add(string.Join(",", ss));
}
File.WriteAllLines(#"C:\Projects\csvExport\csvExport\csvExport\bin\csvFile.csv", list);
}
This code works fine if your XML is having root node with Name "ReportDetails"
Sample XML file for this code to work should be like
<?xml version="1.0"?>
<ReportDetails>
<Sequence>
<SourcePath>
<X>samply x</X>
<Y>xample y</Y>
</SourcePath>
</Sequence>
</ReportDetails>
Your XML is missing "ReportDetails" which you have specified in code
xRoot.ElementName = "ReportDetails";
I have a method which load XML to a XDocument and modify its elements then save.
But when I reload it. I got this error :
Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it.
I checking the XML and see that the XDocument didn't save the changed but create a duplicate and save.
It save the old one and the new one like this example xml :
<?xml version="1.0" encoding="UTF-8"?>
<Ungdungs>
<Ungdung>
<Name>HERE City Lens</Name>
<Id>b0a0ac22-cf9e-45ba-8120-815450e2fd71</Id>
<Path>/Icon/herecitylens.png</Path>
<Version>Unknown</Version>
<Category>HERE</Category>
<Date>Uknown</Date>
</Ungdung>
<?xml version="1.0" encoding="UTF-8"?>
<Ungdungs>
<Ungdung>
<Name>HERE City Lens</Name>
<Id>b0a0ac22-cf9e-45ba-8120-815450e2fd71</Id>
<Path>/Icon/herecitylens.png</Path>
<Version>1.0.0.0</Version>
<Category>HERE</Category>
<Date>Uknown</Date>
</Ungdung>
Here the code I used to modify and save XML :
using (Stream stream = storage.OpenFile("APPSDATA.xml", FileMode.Open, FileAccess.ReadWrite))
{
//var xdoc = XDocument.Load("APPSDATA.xml");
var xdoc = XDocument.Load(stream, LoadOptions.None);
var listapp = from c in xdoc.Descendants("Ungdung") select c;
foreach (XElement app in listapp)
{
var xElement = app.Element("Name");
if (xElement != null)
progressIndicator.Text = "Checking " + xElement.Value + "...";
var element = app.Element("Id");
if (element != null)
{
var appId = element.Value;
var appVersion = await GetAppsVersion(appId);
app.Element("Version").Value = appVersion.ToString();
}
}
xdoc.Save(stream);
}
How can I solve this problem ?
Looks like you're appending modified document at the end of current file content. That's why you can't parse it later again.
I would split read and write parts into different using statements:
XDocument xdoc;
using (Stream stream = storage.OpenFile("APPSDATA.xml", FileMode.Open, FileAccess.Read))
{
xdoc = XDocument.Load(stream, LoadOptions.None);
}
var listapp = from c in xdoc.Descendants("Ungdung") select c;
foreach (XElement app in listapp)
{
var xElement = app.Element("Name");
if (xElement != null)
progressIndicator.Text = "Checking " + xElement.Value + "...";
var element = app.Element("Id");
if (element != null)
{
var appId = element.Value;
var appVersion = await GetAppsVersion(appId);
app.Element("Version").Value = appVersion.ToString();
}
}
using (Stream stream = storage.OpenFile("APPSDATA.xml", FileMode.Truncate, FileAccess.Write))
{
xdoc.Save(stream);
}
Setting FileMode.Truncate on second using statement will clear previous file content, what should fix your problem.
var filename = "C:\\Users\\qadeer.hussain\\Desktop\\gw-msg.log";
var xmlText = new StringBuilder();
bool isXml = false;
foreach (var line in System.IO.File.ReadLines(filename))
{
if (line.Trim().StartsWith("<Message"))
isXml = true;
if (isXml)
{
xmlText.Append(line);
if (line.Trim().EndsWith("</Message>"))
{
//Response.Write(xmlText.ToString());
var xdoc= XDocument.Parse(xmlText.ToString());
xdoc.Save("C:\\Users\\qadeer.hussain\\Desktop\\gw-msg-2.log");
xmlText.Clear();
isXml = false;
}
}
}
i am getting xml data from log file now i have a many xml tag and i am reading that tag when is read a tag i save it into file but the problem is every time my file is overwritten i want my file is not overwritten
using(var writer = File.CreateText(YOUR_FILE_NAME)))
{
....
foreach (var line in System.IO.File.ReadLines(filename))
{
...
//replace xdoc.Save(YOUR_FILE_NAME)
writer.WriteLine(xdoc.ToString());
}
}
By the way. The document you get will not be a valid XML docuemnt. It will be a series of concatinated valid XML documents.
I have two TextBoxes namely txtUserid and txtPassowrd.
I'm writing the values entered in textboxes to a XML file but I do not want the same txtuserid values to be written twice in XML - it should be overwritten.
For example :
If I enter in txtUserid=2 and txtPassword=I
and the second time if I enter txtUserid=2 and txtPassword=m
then I only want one entry to be kept in the XML file :
For the above example: the txtUserid=2 and textPassword=m
The code:
XDocument Xdoc = new XDocument(new XElement("Users"));
if (System.IO.File.Exists("D:\\Users.xml"))
{
Xdoc = XDocument.Load("D:\\Users.xml");
}
else
{
Xdoc = new XDocument();
}
XElement xml = new XElement("Users",
new XElement("User",
new XAttribute("UserId", txtUserName.Text),
new XAttribute("Password", txtPassword.Text)));
if (Xdoc.Descendants().Count() > 0)
{
Xdoc.Descendants().First().Add(xml);
}
else
{
Xdoc.Add(xml);
}
Xdoc.Save("D:\\Users.xml");
Search your existing XML document for a node where the UserId attribute matches your current one, and if it does, modify that one, else make a new one.
I'd imagine that your coude would resemble the following:
List<XElement> list = Xdoc.Descendants("User").Where(el => el.Attribute("UserId").Value == txtUserName.Text).ToList();
if (list.Count == 0)
{
// Add new node
}
else
{
// Modify the existing node
}
Edit: In response to your comment, the code to edit your XElement would look something like
string myValue = "myValue";
list.First().Attribute("ElementName").SetValue(myValue);
Writing textbox values to XML file in C#
protected void btnSave_Click(object sender, EventArgs e)
{
// Open the XML doc
System.Xml.XmlDocument myXmlDocument = new System.Xml.XmlDocument();
myXmlDocument.Load(Server.MapPath("InsertData.xml"));
System.Xml.XmlNode myXmlNode = myXmlDocument.DocumentElement.FirstChild;
// Create new XML element and populate its attributes
System.Xml.XmlElement myXmlElement = myXmlDocument.CreateElement("entry");
myXmlElement.SetAttribute("Userid", Server.HtmlEncode(textUserid.Text));
myXmlElement.SetAttribute("Username", Server.HtmlEncode(textUsername.Text));
myXmlElement.SetAttribute("AccountNo", Server.HtmlEncode(txtAccountNo.Text));
myXmlElement.SetAttribute("BillAmount", Server.HtmlEncode(txtBillAmount.Text));
// Insert data into the XML doc and save
myXmlDocument.DocumentElement.InsertBefore(myXmlElement, myXmlNode);
myXmlDocument.Save(Server.MapPath("InsertData.xml"));
// Re-bind data since the doc has been added to
BindData();
Response.Write(#"<script language='javascript'>alert('Record inserted Successfully Inside the XML File....')</script>");
textUserid.Text = "";
textUsername.Text = "";
txtAccountNo.Text = "";
txtBillAmount.Text = "";
}
void BindData()
{
XmlTextReader myXmlReader = new XmlTextReader(Server.MapPath("InsertData.xml"));
myXmlReader.Close();
}