I'm kinda stuck with reading the value of a xml-file.
The XML looks like:
<?xml version="1.0" encoding="utf-16"?>
<spfFiles>
<file>200_006 xxxxxxx</file>
<file>200_010 xxxxxxx</file>
<file>200_022 xxxxxxx</file>
<file>200_023 xxxxxxx</file>
<file>200_024 xxxxxxx</file>
<file>200_031 xxxxxxx</file>
<file>200_041 xxxxxxx</file>
</spfFiles>
What I'm trying to do is that I want to creat a new Checkbox for each file.
XmlTextReader xReader = new XmlTextReader("spfFiles_simW.xml");
while (xReader.Read())
{
switch (xReader.NodeType)
{
case XmlNodeType.Text: //Display the text in each element.
pnlSPFLIST.Controls.Add(CreateNewCheckBox(xReader.Value));
break;
}
}
The creation of each new element works fine. But I've got trouble with the file names. Each Checkbox only gets the part before the space as a name. For example "200_006". My xmlReader somehow seems to cut the rest of.
Edit:
So here is my CreateNewCheck
private CheckBox CreateNewCheckBox(string sName)
{
label1.Text = sName;
int iExistingCheckBoxX = 0;
int iExistingCheckBoxY = 0;
int iIncrementX = 100;
int iIncrementY = 20;
CheckBox cbNew = new CheckBox();
cbNew.Width = iIncrementX;
if (pnlSPFLIST.Controls.Count == 0)
{
cbNew.Location = new Point(pnlSPFLIST.Location.X, pnlSPFLIST.Location.Y-25);
}
else
{
// Existing checkboxes, so get the Location of the last one.
iExistingCheckBoxX = pnlSPFLIST.Controls[pnlSPFLIST.Controls.Count - 1].Location.X;
iExistingCheckBoxY = pnlSPFLIST.Controls[pnlSPFLIST.Controls.Count - 1].Location.Y;
iExistingCheckBoxX = pnlSPFLIST.Location.X;
iExistingCheckBoxY = iExistingCheckBoxY + iIncrementY + 10;
cbNew.Location = new Point(iExistingCheckBoxX, iExistingCheckBoxY);
}
// Set the Text property according to the input.
cbNew.Text = sName;
return cbNew;
}
Does anyone know where I've gone wrong?
So here is the right solution.
I Just had to change my CreateNewCheckBox-Method:
private CheckBox CreateNewCheckBox(string sName)
{
...
int iIncrementX = 300;
int iIncrementY = 20;
...
}
Just increase the X-Value and everything works fine.
Related
I have created an array of string in an xaml file that I need to use as items in a c# wpf ListBox control. I've tried all kinds of ways to get the items from the array to add to the ListBox, but to no avail. Here's my code:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<string>DocumentSettings.DepositRuntimeDefaults</string>
<string>DocumentSettings.LendingCustomization.CommonSettings</string>
</ArrayOfString>
That's the array, now in my code behind I have a singleton that creates a list:
using System.Collections.Generic;
using System.IO;
namespace csi.Framework.Business
{
public class UIPathOptionsManager
{
public static UIPathOptionsManager Instance = new UIPathOptionsManager();
public List<string> UIPathOptions;
public string theUIPathOptionsFile { get; set; }
public void Initialize(string theDirectory)
{
theUIPathOptionsFile = theDirectory + "\\UIPathOptions.xaml";
if (File.Exists(theUIPathOptionsFile))
{
System.Xml.Serialization.XmlSerializer xmlDeserializer = new
System.Xml.Serialization.XmlSerializer(typeof(List<string>));
TextReader fileReader = new StreamReader(theUIPathOptionsFile);
UIPathOptions = (List<string>)xmlDeserializer.Deserialize(fileReader);
fileReader.Close();
}
}
}
}
And from there I have a ListBox class that I need to populate:
ListBox theUIPathOptionslistBox = new ListBox();
theUIPathOptionslistBox.Items.Add();
theUIPathOptionslistBox.TabIndex = nRow;
theUIPathOptionslistBox.SelectionMode = SelectionMode.Multiple;
theUIPathOptionslistBox.ClipToBounds = true;
theUIPathOptionslistBox.Focusable = true;
theUIPathOptionslistBox.Visibility = Visibility.Hidden;
theUIPathOptionslistBox.Height = 24;
I'm really hoping someone out there can help me out - it feels like I should know this but....
Assign UIPathOptionsManager.Instance.UIPathOptions to ItemSource. Performed this in Window_Loaded Event.
UIPathOptionsManager.Instance.Initialize
(#"C:\Users\Administrator\source\repos\WpfApp9");
ListBox theUIPathOptionslistBox = new ListBox();
theUIPathOptionslistBox.ItemsSource = UIPathOptionsManager.Instance.UIPathOptions;
theUIPathOptionslistBox.TabIndex = nRow;
theUIPathOptionslistBox.SelectionMode = SelectionMode.Multiple;
theUIPathOptionslistBox.ClipToBounds = true;
theUIPathOptionslistBox.Focusable = true;
theUIPathOptionslistBox.Visibility = Visibility.Hidden;
theUIPathOptionslistBox.Height = 24;
You can also do this by creating a property and then use Binding.
I'm trying to read a list of Text nodes from my Xml file. When I try to read the children nodes of 1 of the listed text elements I get the NullReference exception, even though the XDocument nodes are seemingly filled.
The NullReference exception is thrown on the line foreach (XElement textElement in textElements) this means that the list textElements has a Count > 1 so it shouldn't be null. That's as far as the debugger is willing to go.
Am I reading the Xml in the wrong way, or am I not allowed to / shouldn't build the XElement lists the way I am now?
This is my Xml file
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE Book SYSTEM "Book.dtd"[]>
<album version="0.2" settingsVersion="1">
<size />
<cover />
<inner>
<page>
<pagenumber>1</pagenumber>
<image>1.jpg</image>
<text>
<value>Test </value>
<font>arial</font>
<size>18pt</size>
<style>normal</style>
<weight>normal</weight>
<color>#77DD44</color>
<rotation>0</rotation>
<alignment>start</alignment>
<position>
<x>50</x>
<y>50</y>
</position>
</text>
<text>
<value>Test 2 </value>
<font>arial</font>
<size>18pt</size>
<style>normal</style>
<weight>normal</weight>
<color>#77DD44</color>
<rotation>0</rotation>
<alignment>start</alignment>
<position>
<x>50</x>
<y>50</y>
</position>
</text>
</page>
</inner>
</album>
Element inner can hold multiple page elements and page can hold multiple text elements.
I read the Xml in the following method.
List<XElement> pageElements = doc.Root.Element("inner").Elements("page").ToList();
foreach (XElement pageElement in pageElements)
{
string pageNumberString = pageElement.Element("pagenumber").Value;
int pageNumberValue = Convert.ToInt32(pageNumberString);
string fileNameValue = pageElement.Element("image").Value;
// Verify if the currently looped page is the same as the one selected by the user.
if (pageNumberValue == pageNumber)
{
// Get all text nodes from the found page.
List<XElement> textElements = pageElement.Elements("text").ToList();
// If no text nodes found return the page with an empty TextInfo array.
if (textElements.Count == 0)
{
PageInfo pageInfoNoText = new PageInfo { PageNumber = pageNumberValue, FileName = fileNameValue, Text = new TextInfo[0] };
Logger.log("PageInfo found for collection {0}. Info {1}", collectionId, pageInfoNoText);
return pageInfoNoText;
}
// If text nodes are found build a list of TextInfo objects and build a new PageInfo object.
else
{
// All text elements in the XML under the found page.
List<TextInfo> textInfoList = new List<TextInfo>();
TextInfo[] textArray = new TextInfo[0];
#region Load all required text data from the XML file and build the textList.
foreach (XElement textElement in textElements)
{
string textValue = textElement.Element("value").Value;
string fontValue = textElement.Element("font").Value;
string fontSizeValue = textElement.Element("size").Value;
string styleValue = textElement.Element("style").Value;
string weightValue = textElement.Element("weight").Value;
string colorValue = textElement.Element("color").Value;
string rotationString = textElement.Element("rotation").Value;
int rotationValue = Convert.ToInt32(rotationString);
string alignmentValue = textElement.Element("alignment").Value;
string positionXString = textElement.Element("x").Value;
int positionXValue = Convert.ToInt32(positionXString);
string positionYString = textElement.Element("y").Value;
int positionYValue = Convert.ToInt32(positionYString);
// Build Info objects.
PositionInfo tempPositionInfo = new PositionInfo
{
X = positionXValue,
Y = positionYValue
};
TextInfo tempTextInfo = new TextInfo
{
Value = textValue,
Font = fontValue,
Size = fontSizeValue,
Style = styleValue,
Weight = weightValue,
Color = colorValue,
Rotation = rotationValue,
Alignment = alignmentValue,
Position = tempPositionInfo
};
textInfoList.Add(tempTextInfo);
}
textArray = textInfoList.ToArray();
#endregion
PageInfo pageInfo = new PageInfo
{
PageNumber = pageNumberValue,
FileName = fileNameValue,
Text = textArray
};
Logger.log("PageInfo found for collection {0}. Info: {1}", collectionId, pageInfo);
return pageInfo;
}
}
}
Any help / insight is appreciated!
your code is fine but there is a mistake when you get x and y values, you need to get x and y values of position element as below
string positionXString = (string)textElement.Element("position").Element("x").Value;
int positionXValue = Convert.ToInt32(positionXString);
string positionYString = (string)textElement.Element("position").Element("y").Value;
int positionYValue = Convert.ToInt32(positionYString);
your text element does not contain an element called x, so trying to access the value of x results in a NullReferenceException:
string positionXString = textElement.Element("x").Value;
// textElement.Element("x") is null, "x" is in textElement.Element("position")
int positionXValue = Convert.ToInt32(positionXString);
You might be better using Descendants (Descendants("x").FirstOrDefault()?.Value) instead of Element for this, but overall you may want to restructure this altogether.
I want to load an XML file that I make by getting data from my database.
However, if I want to read that data, it says there"s an error on line 1.
Line 1 is strange indeed, because I never asked for "ArrayOfBand". But even when it's there I get all my Bands when i put a break point. It just crashes at the last step. Error HRESULT: 0xC00CE556
XAML on localhost
<ArrayOfBand xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/WindowsStoreApp.Models">
<Band>
<Description>Noorse DJ</Description>
<Facebook>Avicii</Facebook>
<ID>156</ID>
<Name>Avicii</Name>
<Picture>..\Images\Avicii.jpg</Picture>
<Twitter>#Avicii</Twitter>
</Band>
<Band>
<Description>Heavy Metal</Description>
<Facebook>A7X</Facebook>
<ID>157</ID>
<Name>Avenged Sevenfold</Name>
<Picture>..\Images\A7X.jpg</Picture>
<Twitter>#A7X</Twitter>
</Band>
</ArrayOfBand>
C# xml reader
string m_strFilePath = "http://localhost:17281/api/Band";
XmlDocument myXmlDocument = new XmlDocument();
myXmlDocument.Load(m_strFilePath); //Load NOT LoadXml
XmlNodeList elemList = myXmlDocument.GetElementsByTagName("Band");
for (int i = 0; i < elemList.Count; i++)
{
XAML station = new XAML() {
ID = elemList[i].Attributes["ID"].InnerText,
Name = elemList[i].Attributes["Name"].InnerText
};
list.Add(station);
}
return list;
}
c# for creating the xml file
you can see I'm not asking for an "ArrayOfBand". If i take the file and remove "ArrayOfBand" it works perfectly. Anyone has an idea why it's there?
public static List GetBands()
{
List list = new List();
DbDataReader reader = Database.GetData("SELECT * FROM Band");
while (reader.Read())
{
Band b = new Band();
b.ID = reader["ID"].ToString();
b.Name = reader["Name"].ToString();
b.Picture = reader["Picture"].ToString();
b.Description = reader["Description"].ToString();
b.Twitter = reader["Twitter"].ToString();
b.Facebook = reader["Facebook"].ToString();
list.Add(b);
}
return list;
}
Your xml is badly formed. You need to have a closing </ArrayOfBand> at the end.
I have used some code a couple times in testing and it seems to work well. Now I am working on a helper app for a game and trying to apply the same code, but it is failing. I need to know if there is some error I am overlooking. I am trying to read from an xml file and populate text boxes and combo boxes in my winform. I pull the name correctly, but the remaining attributes do not populate. Here is an example of my code:
public bool LoadChar(string _filename) //Fetches character stats from xml file and loads to the textboxes
{
try
{
_name = tbName.Text;//hero
XmlDocument doc = new XmlDocument();//hero
doc.Load(_filename);//hero
XmlNode _currNode = doc.SelectSingleNode("/Characters/Char[#name='" + _name + "']");//hero
_currNode.Attributes["st"].Value = _st;
_currNode.Attributes["dx"].Value = _dx;
_currNode.Attributes["iq"].Value = _iq;
_currNode.Attributes["ma"].Value = _ma;
_currNode.Attributes["armor"].Value = _armor;
_currNode.Attributes["hits"].Value = _hits;
_currNode.Attributes["wounds"].Value = _wounds;
_currNode.Attributes["fatigue"].Value = _fatigue;
_currNode.Attributes["attack"].Value = _attack;
_currNode.Attributes["dmgdie"].Value = _dmgdie;
_currNode.Attributes["dmgmod"].Value = _dmgmod;
_currNode.Attributes["exp"].Value = _exp;
_currNode.Attributes["description"].Value = _description;
_currNode.Attributes["equipment_money"].Value = _equipmentmoney;
_currNode.Attributes["weapons_armor"].Value = _wpnarmor;
_currNode.Attributes["talents_spells"].Value = _talentspell;
_currNode.Attributes["gender"].Value = _gender;
_currNode.Attributes["race"].Value = _race;
_currNode.Attributes["type"].Value = _type;
_currNode.Attributes["job"].Value = _job;
tbName.Text = _name;
tbSt.Text = _st;
tbDx.Text = _dx;
tbIq.Text = _iq;
tbMa.Text = _ma;
tbArmor.Text = _armor;
tbHitStop.Text = _hits;
tbWounds.Text = _wounds;
tbFatigue.Text = _fatigue;
tbAttack.Text = _attack;
tbDmgDie.Text = _dmgdie;
tbDmgMod.Text = _dmgmod;
tbExp.Text = _exp;
tbDescription.Text = _description;
tbEquipmentMoney.Text = _equipmentmoney;
tbWeaponArmor.Text = _wpnarmor;
tbTalentSpell.Text = _talentspell;
cbGender.SelectedValue = _gender;
cbRace.SelectedValue = _race;
cbType.SelectedValue = _type;
cbJob.SelectedValue = _job;
return true;
}
catch
{
return false;
}
}
Here is the xml file I am attempting to get the data from:
<?xml version="1.0" encoding="UTF-8" ?>
- <Characters>
<Char name="Conan" st="15" dx="13" iq="8" ma="10" armor="Leather" hits="2" wounds="2"
fatigue="0" attack="Great Sword" dmgdie="3" dmgmod="+2" exp="69" description="Conan is a
big enthusiastic gentleman" equipment_money="Backpack, 4 gold coins."
weapons_armor="Great Sword, Longbow." talents_spells="Killing, Maiming, Strangling,
Boxing, Florist." gender="Male" race="Human" type="Barbarian" job="Unskilled" />
</Characters>
I created the xml file by writing the textboxes and comboboxes in my form to the xml, but now I want to load a character from the xml and it is not working in this example. I do have it working in another example and I have compared the two closely together, but can not find any real differences besides this example having more and different attributes.
Note: I placed a breakpoint and the _name value pulls "Conan" but all other values are null.
I intend to refine this later at some point--just bashing it out right now.
You are not loading data from XML. To read data you need to change places like this:
public bool LoadChar(string _filename) //Fetches character stats from xml file and loads to the textboxes
{
try
{
_name = tbName.Text;//hero
XmlDocument doc = new XmlDocument();//hero
doc.Load(_filename);//hero
XmlNode _currNode = doc.SelectSingleNode("/Characters/Char[#name='" + _name + "']");//hero
//reading attributes values
_st = _currNode.Attributes["st"].Value;
_dx = _currNode.Attributes["dx"].Value;
_iq = _currNode.Attributes["iq"].Value;
_ma = _currNode.Attributes["ma"].Value;
_armor = _currNode.Attributes["armor"].Value;
_hits = _currNode.Attributes["hits"].Value;
_wounds = _currNode.Attributes["wounds"].Value;
_fatigue = _currNode.Attributes["fatigue"].Value;
_attack = _currNode.Attributes["attack"].Value;
_dmgdie = _currNode.Attributes["dmgdie"].Value;
_dmgmod = _currNode.Attributes["dmgmod"].Value;
_exp = _currNode.Attributes["exp"].Value;
_description = _currNode.Attributes["description"].Value;
_equipmentmoney = _currNode.Attributes["equipment_money"].Value;
_wpnarmor = _currNode.Attributes["weapons_armor"].Value;
_talentspell = _currNode.Attributes["talents_spells"].Value;
_gender = _currNode.Attributes["gender"].Value;
_race = _currNode.Attributes["race"].Value;
_type = _currNode.Attributes["type"].Value;
_job = _currNode.Attributes["job"].Value;
tbName.Text = _name;
tbSt.Text = _st;
tbDx.Text = _dx;
tbIq.Text = _iq;
tbMa.Text = _ma;
tbArmor.Text = _armor;
tbHitStop.Text = _hits;
tbWounds.Text = _wounds;
tbFatigue.Text = _fatigue;
tbAttack.Text = _attack;
tbDmgDie.Text = _dmgdie;
tbDmgMod.Text = _dmgmod;
tbExp.Text = _exp;
tbDescription.Text = _description;
tbEquipmentMoney.Text = _equipmentmoney;
tbWeaponArmor.Text = _wpnarmor;
tbTalentSpell.Text = _talentspell;
cbGender.SelectedValue = _gender;
cbRace.SelectedValue = _race;
cbType.SelectedValue = _type;
cbJob.SelectedValue = _job;
return true;
}
catch
{
return false;
}
}
This function (look CODE) occur when xml file is downloaded from my server.. Now I want to load it in my local database...
XML
<?xml version="1.0" encoding="utf-8" ?>
<Questions>
<idQuestion>1</idQuestion>
<Question>Question 1</Question>
<CorrectAns>Ans1</CorrectAns>
<WrongAns1>Ans2</WrongAns1>
<WrongAns2>Ans3</WrongAns2>
<WrongAns3>Ans4</WrongAns3>
<Category>CategoryName</Category>
</Questions>
<Questions>
<idQuestion>2</idQuestion>
<Question>Question 2</Question>
<CorrectAns>Ans1</CorrectAns>
<WrongAns1>Ans2</WrongAns1>
<WrongAns2>Ans3</WrongAns2>
<WrongAns3>Ans4</WrongAns3>
<Category>CategoryName</Category>
</Questions>
etc...
CODE:
void downloader_Completed(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
return;
XElement quest = XElement.Parse(e.Result);
using (QuestionContext context = new QuestionContext(ConnectionString))
{
for (int i = 0; i < quest.Length; i++)
{
Question q = new Question();
q.idQuestion = ;
q.Question = ;
q.CorrectAns = ;
q.WrongAns1 = ;
q.WrongAns2 = ;
q.WrongAns3 = ;
context.QuestionsDB.InsertOnSubmit(q);
context.SubmitChanges();
}
}
}
I have 2 questions:
1)How to read the xml content and write them in:
q.idQuestion = ;
q.Question = ;
q.CorrectAns = ;
q.WrongAns1 = ;
q.WrongAns2 = ;
q.WrongAns3 = ;
2)for (int i = 0; i < quest.Length; i++) Herequest.Length give error (I know why)... How to make custom function to get the length? I need it to count <Questions> tags
Your xaml is not in valid format, because it has multiple root elements (Questions).
Assuming if it is in the correct format like this (I have modifiec)
string xmlData = #"<?xml version=""1.0"" encoding=""utf-8"" ?>
<Questions>
<Question>
<idQuestion>1</idQuestion>
<QuestionName>Question 1</QuestionName>
<CorrectAns>Ans1</CorrectAns>
<WrongAns1>Ans2</WrongAns1>
<WrongAns2>Ans3</WrongAns2>
<WrongAns3>Ans4</WrongAns3>
<Category>CategoryName</Category>
</Question>
<Question>
<idQuestion>2</idQuestion>
<QuestionName>Question 2</QuestionName>
<CorrectAns>Ans1</CorrectAns>
<WrongAns1>Ans2</WrongAns1>
<WrongAns2>Ans3</WrongAns2>
<WrongAns3>Ans4</WrongAns3>
<Category>CategoryName</Category>
</Question>
</Questions>";
You can have any number of tags as above
Now, you can convert this data into classes as shown below
XElement quest = XElement.Parse(xmlData);
var questionsData = from qn in quest.Descendants("Question")
select new Question
{
idQuestion = int.Parse(qn.Element("idQuestion").Value),
QuestionName = qn.Element("QuestionName").Value,
CorrectAns = qn.Element("CorrectAns").Value,
WrongAns1 = qn.Element("WrongAns1").Value,
WrongAns2 = qn.Element("WrongAns2").Value,
WrongAns3 = qn.Element("WrongAns3").Value
};
var Questions = questionsData.ToList();
var noofquestions = Questions.Count;
//If you want any question with specific id, say '2'
int idQuestion = 2;
var question = Questions.Where(item => item.idQuestion == idQuestion).First();
Here my Question class is like this
class Question
{
public int idQuestion ;
public string QuestionName ;
public string CorrectAns ;
public string WrongAns1 ;
public string WrongAns2 ;
public string WrongAns3 ;
}
Now apply the above process to your data, in whatever way applies