加载XML的异常

时间:2016-09-15 13:26:44

标签: c# xml

我正在使用此代码来保存和恢复XML值,但我遇到了麻烦。当我尝试加载XML时,Rescue通常会解决问题。我在图片中得到了这个例外。

enter image description here

第105行:字符串文字= el.Attribute(“文字”)。值;

        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();
        }

2 个答案:

答案 0 :(得分:2)

异常是明确的:没有这样的属性el.Attribute(“Text”),所以你不能试图获得它的价值。在获取属性之前检查属性是否存在。

答案 1 :(得分:0)

经过研究可以解决这个问题。

解决方案:

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();
        }
相关问题