首页 > 解决方案 > XML Attribute to Winforms TextBox

问题描述

I have tried looking at other related articles but can't seem to get my head round how to pass an XML attribute to a TextBox in WinForms. I am relatively new to XML so please bear with.

The XML file looks like this;

<root>

  <!--schema to help some xml editors, do not change-->
    <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
        <xsd:element name="root" msdata:IsDataSet="true">
            <xsd:complexType>
                <xsd:choice maxOccurs="unbounded">
                    <xsd:element name="data">
                        <xsd:complexType>
                            <xsd:sequence>
                                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
                            </xsd:sequence>
                            <xsd:attribute name="name" type="xsd:string" />
                        </xsd:complexType>
                    </xsd:element>                  
                </xsd:choice>
            </xsd:complexType>
        </xsd:element>
    </xsd:schema>
    

    <data name="LoginPageUserName">
    <value>Student ID</value>
    </data>
    
    <data name="OpenDate">
    <value>22-Nov-2021</value>
    </data>
    
    <data name="CloseDate">
    <value>22-Dec-2021</value>
    </data>

    <data name="RuleDescriptionMinMaxSame">
    <value>Please make your module selections as per your Programme specifications</value>
    </data>

</root>

What I would like to do is pass the OpenDate and CloseDate to two texboxes in WinForms (i.e. 22-Nov-2021 to textbox1 and 22-Dec-2021 to textBox2). So far what I have is;

private void button4_Click(object sender, EventArgs e)
        {
doc = new XmlDocument();
            root = doc.DocumentElement;
            doc.Load(PATH);
            XmlNodeList elemList = doc.GetElementsByTagName("OpenDate");
for (int i = 0; i < elemList.Count; i++)
{
    string attrVal = elemList[i].Attributes["OpenDate"].Value;
    txtBxFromDate.Text = attrVal ;
}

textBox1.Text = doc.SelectSingleNode("/root/@OpenDate").Value;
textBox2.Text = doc.SelectSingleNode("/root/@CloseDate").Value;
}

I declared the path and document in the public partial class;

private XmlDocument doc;
private XmlElement root;
public string PATH = @"\\servername\Student\StudentCustomStrings.xml";

I keep getting an 'Object reference not set to an instance of an object.' error message and I am now at a loss.

I have used 'servername' in this case as I did not deem it wise to put the actual server name, so please disregard that part.

Your help would be greatly appreciated.

Thank you in advance.

标签: c#xmlwinforms

解决方案


推荐阅读