In the following code, I am trying to do a text parsing by using a streamreader. This is to get the email address from the text file. If i have no email address, combobox is left blank (index = -1). If i have a email that is found in my xml file, then i will select it. Else, i will add a node to my xml file with the new email address.
code:
private void Textparsing()
{
using (StreamReader sr = new StreamReader(Masterbuildpropertiespath))
{
while (sr.Peek() >= 0)
if (line.StartsWith("Builder_Email:"))
{
string[] fields = line.Split('\t');
string builderemail = fields[3];
XmlDocument emailparse = new XmlDocument();
emailparse.LoadXml(@"C:\GUI\buildermanageremail.xml");
XmlNodeList emailnode = emailparse.GetElementsByTagName("value");
if (string.IsNullOrEmpty(builderemail))
comboBox1.SelectedIndex = -1;
else
foreach (XmlNode node in emailnode)
{
if (builderemail == node.InnerText)
{
int count = emailparse.SelectNodes("email/builderemail/builder").Count;
count--;
comboBox1.SelectedIndex = count;
}
else
{
//create main node
XmlNode abc = emailparse.CreateNode(XmlNodeType.Element, "builder", null);
//create the first child node
XmlNode value = emailparse.CreateElement("value");
//set the value
value.InnerText = builderemail;
// add childes to father
//node.AppendChild(id);
开发者_StackOverflow社区 abc.AppendChild(value);
// find the node we want to add the new node to
XmlNodeList l = emailparse.GetElementsByTagName("builderemail");
// append the new node
l[0].AppendChild(abc);
// save the file
emailparse.Save(@"C:\GUI\buildermanageremail.xml");
//then we populate the new updated xml file into the drop down list:
PopulateDDLFromXMLFile();
int count = emailparse.SelectNodes("email/builderemail/builder").Count;
count--;
comboBox1.SelectedIndex = count;
}
}
}
However, I get an XmlException (Data at the root level is invalid. Line 1, position 1.) at this line:
emailparse.LoadXml(@"C:\GUI\buildermanageremail.xml");
Why is that so?
my xmlfile:
<?xml version="1.0" encoding="utf-8"?>
<email>
<builderemail>
<builder>
<value>abc@123.com</value>
</builder>
<builder>
<value>Others</value>
</builder>
</builderemail>
<manageremail>
<manager>
<value>abc@456.com</value>
</manager>
<manager>
<value>Others</value>
</manager>
</manageremail>
</email>
You should use the
emailparse.Load(@"C:\GUI\buildermanageremail.xml");
method instead of
emailparse.LoadXml(@"C:\GUI\buildermanageremail.xml");
since LoadXml can load xml string, not the file.
精彩评论