【问题标题】:Textbox string to xml issue文本框字符串到 xml 问题
【发布时间】:2013-10-14 22:16:48
【问题描述】:

我在使用 Windows 窗体应用程序中的 C# 代码格式化我的 xml 文件时遇到了一点问题。这是我用于这个项目的代码:

private void btnSend_Click(object sender, EventArgs e)
    {
        string _name = tbName.ToString();
        string _st = tbSt.ToString();
        string _dx = tbDx.ToString();
        string _iq = tbIq.ToString();
        string _filename = @"c:\Add.xml";

        if (File.Exists(_filename))
        {
            XDocument xDoc = XDocument.Load(_filename);
            xDoc.Root.Add(new XElement("character",                                
                            new XElement("name", _name),
                            new XElement("st", _st),
                            new XElement("dx", _dx),
                            new XElement("iq", _iq)
                        ));
            xDoc.Save(_filename);
        }

        else if (!File.Exists(_filename))
        {

            XmlDocument doc = new XmlDocument();
            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(docNode);

            XmlNode productsNode = doc.CreateElement("characters");
            doc.AppendChild(productsNode);

            XmlNode productNode = doc.CreateElement("character");
            productsNode.AppendChild(productNode);
            XmlNode nmNode = doc.CreateElement("name");
            nmNode.AppendChild(doc.CreateTextNode(_name));
            productNode.AppendChild(nmNode);
            XmlNode stNode = doc.CreateElement("st");
            stNode.AppendChild(doc.CreateTextNode(_st));
            productNode.AppendChild(stNode);
            XmlNode dxNode = doc.CreateElement("dx");
            dxNode.AppendChild(doc.CreateTextNode(_dx));
            productNode.AppendChild(dxNode);
            XmlNode iqNode = doc.CreateElement("iq");
            iqNode.AppendChild(doc.CreateTextNode(_iq));
            productNode.AppendChild(iqNode);

            doc.Save(@"c:\Add.xml");//must have to save

        }
    }

问题是我的 .xml 文件附带了整个 TextBox 类前缀,例如:

...

- <character>
    <name>System.Windows.Forms.TextBox, Text: bob</name> 
    <st>System.Windows.Forms.TextBox, Text: 10</st> 
    <dx>System.Windows.Forms.TextBox, Text: 12</dx> 
    <iq>System.Windows.Forms.TextBox, Text: 08</iq> 
</character>

我想让它看起来像这样:

- <character>
    <name>bob</name> 
    <st>10</st> 
    <dx>12</dx> 
    <iq>08</iq> 
</character>

如果你们中的任何一位知识渊博的人能伸出援手(或指向我一个链接),我将不胜感激。我确实梳理了谷歌,但没有发现这个特定的奇怪问题。非常感谢您提供的任何帮助。

【问题讨论】:

    标签: c# xml formatting read-write


    【解决方案1】:

    明显的我没有看到。感谢那些可能会回应的人。现在我贴出来了,很明显。

    变化

    string _name = tbName.ToString();
    

    只是

    string _name = tbName.Text;
    

    当然解决了这个问题。希望这对其他人有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      相关资源
      最近更新 更多