Can't find a path to my xml file - c#

I'm trying to find a my XML file called ClassData.xml, but can't find it. The file itself is hidden in a folder called Data. I don't know how to get to the directory of my project where the file is. I'm using ios simulator.
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
this.lbl_Werkt.Text = "het werkt wtf";
XmlDocument Doc = new XmlDocument();
try
{
Doc.Load("/Data/ClassData.xml");
}
catch (Exception error)
{
Console.WriteLine("The File could not be read:");
Console.WriteLine(error.Message);
}
finally
{
foreach (XmlNode node in Doc.SelectNodes("//Warrior"))
{
string Name = node["Name"].InnerText;
lbl_Name.Text = Name;
}
}
}

I have been really dumb! If someone else has this problem, look at your file (In my case xml) and change the build action from Embedded to Content. If you do this you can just do this:
Doc.Load(#"\Data\ClassData.xml");

For a file in your project, try this:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
this.lbl_Werkt.Text = "het werkt wtf";
try{
XmlDocument Doc = new XmlDocument();
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"Data\ClassData.xml");
if(!file.Exists(path))
throw new IOExpection("File not found");
Doc.Load(path);
foreach (XmlNode node in Doc.SelectNodes("//Warrior"))
{
string Name = node["Name"].InnerText;
lbl_Name.Text = Name;
}
}
catch(IOException ioEx)
{
Console.WriteLine("The File could not be read:");
Console.WriteLine(ioEx.Message);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}

Related

Export an XML content from a TextBox into an XML file

I am trying to create an application that imports an XML file into a TextBox, with the goal to edit the content.
After editing, the user should be able to save the content of the file, but at the same time to validate it. For example,
<Person id="22">
<Name gg="u">John</Name>
<Surname>Jones</Surname>
<PhoneNo>333333333111</PhoneNo>
<Country>Germany</Country>
</Person>
If the user edits the start tag "Name", but forgets to edits the end tag, it should throw an exception.
I have tried
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(MyTextBox.Text);
xmlDoc.Save(fileName);
and
XmlElement DocRoot = xmlDoc.CreateElement("root");
DocRoot.InnerText = MyTextBox.Text;
xmlDoc.AppendChild(DocRoot);
xmlDoc.Save(fileName);
None worked. I am grateful for any help, thank you!
I have though of this solution and it seems to work :) As per the xsd question, I have a generic XML.
try
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(MyTextBox.Text);
XmlWriterSettings settings = new XmlWriterSettings
{
Indent = true
};
XmlWriter writer = XmlWriter.Create(fileName, settings);
xmlDoc.Save(writer);
MessageBox.Show("File overwritten to: " + fileName);
}
catch (Exception ex)
{
MessageBox.Show("The textbox content is wrong. ");
}
Seems that you are trying to check if the XML text is well formed and not really if it is valid against a certain definition.
To check if the XML text is well formed, you can try to parse it and verify if it contains any errors. Here is a function that attempts to do that:
class Program
{
static void Main(string[] args)
{
var result = ValidateXml("<Person id=\"22\"><Name>John<Name></Person>");
if (!result.IsValid)
{
Console.WriteLine($"Line number: {result.Exception.LineNumber}");
Console.WriteLine($"Line position: {result.Exception.LinePosition}");
Console.WriteLine($"Message: {result.Exception.Message}");
}
// OUTPUT:
// Line number: 1
// Line position: 35
// Message: The 'Name' start tag on line 1 position 28 does not match the end tag of 'Person'.Line 1, position 35.
}
static ValidationResult ValidateXml(string xml)
{
using (var xr = XmlReader.Create( new StringReader(xml)))
{
try
{
while (xr.Read())
{
}
return ValidationResult.ValidResult;
}
catch (XmlException exception)
{
return new ValidationResult(exception);
}
}
}
public class ValidationResult
{
public static ValidationResult ValidResult = new ValidationResult();
private ValidationResult()
{
IsValid = true;
}
public ValidationResult(XmlException exception)
{
IsValid = false;
Exception = exception;
}
public bool IsValid { get; }
public XmlException Exception { get;}
}
}

How to properly xml serialize (with the correct schema)

I have a class that I deserialize with:
public static bool FileDeserializer<T>(string xmlFileName, out T element, out string strError)
{
try
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
using (TextReader reader = new StreamReader(xmlFileName))
{ element = (T)xmlSerializer.Deserialize(reader); }
strError = string.Empty;
return true;
}
catch (Exception exc)
{
strError = "XmlFileDeserializer exception: " + exc;
element = default(T);
return false;
}
}
and serialize with
public static bool FileSerializer<T>(T value, string strFilename, out string strError)
{
try
{
var serializer = new XmlSerializer(typeof(T));
using (var xmlWriter = XmlWriter.Create(strFilename))
{ serializer.Serialize(xmlWriter, value); }
strError = string.Empty;
return true;
}
catch (Exception exc)
{
strError = "XmlFileSerializer exception: " + exc;
return false;
}
}
Now everything works fine with serialize/deserialize.
But when I try to read it to modify it:
with visual studio it's on a single line (so very hard to read)
with an other editor (xml explorer) i get the message:
The document does not have a specified schema. Click to apply one.
So I have searched for documentation but didn't understand how to put that in my code.
Thanks
---ADD---
Here is the xml in question sorry for not having added it before
<?xml version="1.0" encoding="utf-8"?><CfgData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><DialogFileIniDir>C:\temp</DialogFileIniDir><HorSplitterPos>204</HorSplitterPos><VerSplitterPos>358</VerSplitterPos><GridStep>10</GridStep><Scale>0</Scale><TraceThickness>3</TraceThickness><ShadowsEnabled>false</ShadowsEnabled><Theme>LIGHT</Theme><LightForeground><A>255</A><R>0</R><G>0</G><B>0</B><ScA>1</ScA><ScR>0</ScR><ScG>0</ScG><ScB>0</ScB></LightForeground><LightBackgound><A>255</A><R>245</R><G>245</G><B>245</B><ScA>1</ScA><ScR>0.913098633</ScR><ScG>0.913098633</ScG><ScB>0.913098633</ScB></LightBackgound><LightTraceOkColor><A>255</A><R>255</R><G>255</G><B>255</B><ScA>1</ScA><ScR>1</ScR><ScG>1</ScG><ScB>1</ScB></LightTraceOkColor><LightTraceCancelColor><A>255</A><R>255</R><G>0</G><B>255</B><ScA>1</ScA><ScR>1</ScR><ScG>0</ScG><ScB>1</ScB></LightTraceCancelColor><LightTraceEndColor><A>255</A><R>0</R><G>0</G><B>255</B><ScA>1</ScA><ScR>0</ScR><ScG>0</ScG><ScB>1</ScB></LightTraceEndColor><LightHeaderUnselectedBG><A>255</A><R>0</R><G>206</G><B>209</B><ScA>1</ScA><ScR>0</ScR><ScG>0.6172066</ScG><ScB>0.637596846</ScB></LightHeaderUnselectedBG><LightHeaderSelectedBG><A>255</A><R>0</R><G>0</G><B>255</B><ScA>1</ScA><ScR>0</ScR><ScG>0</ScG><ScB>1</ScB></LightHeaderSelectedBG><LightHeaderStartEndBG><A>255</A><R>105</R><G>105</G><B>105</B><ScA>1</ScA><ScR>0.141263291</ScR><ScG>0.141263291</ScG><ScB>0.141263291</ScB></LightHeaderStartEndBG><LightHeaderFG><A>255</A><R>255</R><G>255</G><B>255</B><ScA>1</ScA><ScR>1</ScR><ScG>1</ScG><ScB>1</ScB></LightHeaderFG><LightBlockBG><A>255</A><R>220</R><G>220</G><B>220</B><ScA>1</ScA><ScR>0.7156935</ScR><ScG>0.7156935</ScG><ScB>0.7156935</ScB></LightBlockBG><LightBlockFG><A>255</A><R>255</R><G>255</G><B>255</B><ScA>1</ScA><ScR>1</ScR><ScG>1</ScG><ScB>1</ScB></LightBlockFG><DarkForeground><A>255</A><R>255</R><G>255</G><B>255</B><ScA>1</ScA><ScR>1</ScR><ScG>1</ScG><ScB>1</ScB></DarkForeground><DarkBackgound><A>255</A><R>19</R><G>56</G><B>53</B><ScA>1</ScA><ScR>0.00651209056</ScR><ScG>0.0395462364</ScG><ScB>0.0356013142</ScB></DarkBackgound><DarkTraceOkColor><A>255</A><R>255</R><G>255</G><B>255</B><ScA>1</ScA><ScR>1</ScR><ScG>1</ScG><ScB>1</ScB></DarkTraceOkColor><DarkTraceCancelColor><A>255</A><R>255</R><G>0</G><B>255</B><ScA>1</ScA><ScR>1</ScR><ScG>0</ScG><ScB>1</ScB></DarkTraceCancelColor><DarkTraceEndColor><A>255</A><R>0</R><G>0</G><B>255</B><ScA>1</ScA><ScR>0</ScR><ScG>0</ScG><ScB>1</ScB></DarkTraceEndColor><DarkHeaderUnselectedBG><A>255</A><R>220</R><G>220</G><B>220</B><ScA>1</ScA><ScR>0.7156935</ScR><ScG>0.7156935</ScG><ScB>0.7156935</ScB></DarkHeaderUnselectedBG><DarkHeaderSelectedBG><A>255</A><R>0</R><G>0</G><B>255</B><ScA>1</ScA><ScR>0</ScR><ScG>0</ScG><ScB>1</ScB></DarkHeaderSelectedBG><DarkHeaderStartEndBG><A>255</A><R>105</R><G>105</G><B>105</B><ScA>1</ScA><ScR>0.141263291</ScR><ScG>0.141263291</ScG><ScB>0.141263291</ScB></DarkHeaderStartEndBG><DarkHeaderFG><A>255</A><R>255</R><G>255</G><B>255</B><ScA>1</ScA><ScR>1</ScR><ScG>1</ScG><ScB>1</ScB></DarkHeaderFG><DarkBlockBG><A>255</A><R>220</R><G>220</G><B>220</B><ScA>1</ScA><ScR>0.7156935</ScR><ScG>0.7156935</ScG><ScB>0.7156935</ScB></DarkBlockBG><DarkBlockFG><A>255</A><R>255</R><G>255</G><B>255</B><ScA>1</ScA><ScR>1</ScR><ScG>1</ScG><ScB>1</ScB></DarkBlockFG></CfgData>

Exception loading the XML

I'm using this code to save and restore the XML values ​​but I'm in trouble . Rescue usually works the problem and when I try to load the XML . I get this exception that in the image.
line 105 : string text = el.Attribute("Text").Value;
void SaveData() {
XDocument xmlDocument = new XDocument(new XElement("Pages"));
List<XElement> xmlPages = new List<XElement>();
foreach(KeyValuePair<string, string> doc in documents)
xmlDocument.Root.Add(
new XElement("Page",
new XAttribute("nodeName", GetNodeName(doc.Key)),
new XAttribute("pageGuid", doc.Key),
new XAttribute("Rtf", doc.Value)));
xmlDocument.Root.Add(
new XElement("TextEdit",
new XAttribute("Text", textBox1.Text)));
xmlDocument.Save(GetPathToFile());
}
void LoadData() {
try {
XDocument xmlDocument = XDocument.Load(GetPathToFile());
rootNode.Nodes.Clear();
documents.Clear();
foreach(XElement el in xmlDocument.Root.Elements()) {
string nodeName = el.Attribute("nodeName").Value;
string pageGuid = el.Attribute("pageGuid").Value;
string rtf = el.Attribute("Rtf").Value;
string text = el.Attribute("Text").Value;
rootNode.Nodes.Add(new DataNode(nodeName, pageGuid));
documents.Add(pageGuid, rtf);
textBox1.Text = text;
}
} catch(Exception ex) {
MessageBox.Show("No data loaded. Check XML file" + ex.ToString());
}
treeList1.RefreshDataSource();
}
The exception is clear: There is not such attribute el.Attribute("Text"), so you can't try to get it's value. Check for attribute existence before getting it's value.
After research could solve the case.
Solution:
void LoadData() {
try {
XDocument xmlDocument = XDocument.Load(GetPathToFile());
rootNode.Nodes.Clear();
documents.Clear();
foreach(XElement el in xmlDocument.Root.Elements()) {
switch(el.Name.LocalName) {
case "Page":
string nodeName = el.Attribute("nodeName").Value;
string pageGuid = el.Attribute("pageGuid").Value;
string rtf = el.Attribute("Rtf").Value;
rootNode.Nodes.Add(new DataNode(nodeName, pageGuid));
documents.Add(pageGuid, rtf);
break;
case "Text":
textEdit1.Text = el.Attribute("text").Value;
break;
}
}
} catch(Exception ex) {
MessageBox.Show("No data loaded. Check XML file");
}
treeList1.RefreshDataSource();
}

Is there any way to make my C# XMLManager work?

so I'm a total noob to C# is there any way to make this work?
It would also be a great help if someone could explain why my system doesn't work, and why another version would.
using System;
using System.Xml;
public class XMLManager
{
private XmlTextReader reader;
private XmlDocument document;
private XmlNodeList nodeList;
public void OpenFile(string file)
{
try
{
reader = new XmlTextReader(file);
reader.WhitespaceHandling = WhitespaceHandling.None;
reader.MoveToContent();
document = new XmlDocument();
document.Load(reader);
nodeList = document.SelectNodes(#"Settings/Settings");
}
catch (System.IO.FileNotFoundException)
{
}
}
public void CloseFile()
{
if (reader != null)
{
((IDisposable)reader).Dispose();
reader.Close();
reader = null;
}
document = null;
nodeList = null;
}
public string Get(string attrib)
{
for (int i = 0; i < nodeList.Count; i++)
{
reader.MoveToAttribute(i);
if (reader.Name == attrib)
{
return reader.Value;
}
}
return null;
}
}
Edit: Sorry for my bad formatting, this is my first time posting on Stack Overflow.
You are making multiple mistakes here.
First of all, you don't need a reader to read xml content into an XmlDocument.
Second, while trying to get the attributes, you are trying to proceed to the attributes using the reader which is obviously not having the context of the selected nodes.
Here is your updated XmlManager, but I have to note, there is a logical error too, which is, when the GetAttribute is invoked, you are searching all the Settings/Settings nodes and if find the attribute in any of them, return it. If the xml file contains only one Settings/Settings node, SelectSingleNode is better. I assume the following format:
<Settings>
<Settings attr1="attr1val" attr2="attr2val" />
</Settings>
Note: I also removed CloseFile method because it is no longer required.
public class XMLManager
{
private XmlDocument document;
private XmlNodeList nodeList;
public void OpenFile(string file)
{
document = new XmlDocument();
document.Load(file);
nodeList = document.SelectNodes(#"Settings/Settings");
}
public string Get(string attrib)
{
for (int i = 0; i < nodeList.Count; i++)
{
if (nodeList[i].Attributes[attrib] != null)
{
return nodeList[i].Attributes[attrib].Value;
}
}
return null;
}
}
Overall, you're doing way too much work.
If you have XML in a file, load it directly into an XML (DOM) object using XmlDocument.Load( strFileName );
To iterate all nodes matching an XPath query, see how I run through them.
try {
string strFileName = HttpContext.Current.Server.MapPath("\\data.xml");
XmlDocument xml = new XmlDocument();
xml.Load( strFileName );
foreach (XmlElement ndRow in xml.SelectNodes("//row")) {
string strTemp = ndRow.GetAttribute("foo");
}
} catch (Exception ex) {
Response.Write(ex.Message);
}

Does WebBrowser.DocumentText as well contains all frame documents text?

I am not sure if WebBrowser.DocumentText contains only top document source or frames document text also included. Could not find that from MSDN page.
No it does not. I have tried next:
DocumentText:
File.WriteAllText(#"C:\doc.txt", webBrowser1.DocumentText, Encoding.UTF8);
GetElementsByTagName("HTML")
HtmlElement elem;
if (webBrowser1.Document != null)
{
HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("HTML");
if (elems.Count == 1)
{
elem = elems[0];
string pageSource = elem.OuterHtml;
File.WriteAllText(#"C:\doc.txt", pageSource, Encoding.UTF8);
}
}
IOleCommandTarget
public void ShowSource()
{
IOleCommandTarget cmdt = null;
object o = null;
object oIE = null;
try {
cmdt = (IOleCommandTarget)this.Document.DomDocument;
cmdt.Exec(cmdGUID, oCommands.ViewSource, 1, o, o);
} catch (Exception ex) {
throw new Exception(ex.Message.ToString(), ex.InnerException);
} finally {
cmdt = null;
}
}
The only way is to go through all frame documents.
Updated If iframe has different url you will get UnauthorizedAccessException when trying to retrieve iframe document

Categories

Resources