我是delphi的新手,现在我必须阅读创建一个xml.我的代码如下:
单位writexml1;
interface uses Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,Dialogs,xmldom,XMLIntf,StdCtrls,msxmldom,XMLDoc; type TForm1 = class(TForm) XMLDocument1: TXMLDocument; Button1: TButton; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.SaveClick(Sender: TObject); var rootName: String; childNode: String; attrChild: string; iXml: IDOMDocument; iRoot,iNode,iNode2,iChild,iAttribute: IDOMNode; XMLDoc: TXMLDocument; begin XMLDoc.Active := False; XMLDoc.XML.Text := ''; XMLDoc.Active := True; XMLDoc.SaveToFile('C:\Documents and Settings\a\Desktop\zulfa.xml'); iXml := XMLDoc.DOMDocument; iRoot := iXml.appendChild(iXml.createElement('xml')); iNode := iRoot.appendChild(iXml.createElement('test')); iNode.appendChild(iXml.createElement('test2')); iChild := iNode.appendChild(iXml.createElement('test3')); iChild.appendChild(iXml.createElement('Simple calue')); iNode.insertBefore(iXml.createElement('test4'),iChild); iNode2 := iNode.cloneNode(True); iRoot.appendChild(iNode2); iAttribute := iXml.createAttribute('color'); iAttribute.nodeValue := 'red'; iNode2.attributes.setNamedItem(iAttribute); end; end.
问题是,在单击保存按钮时会显示异常,例外是
06001
解决方法
你的代码看起来有点复杂.我建议:忘记TXMLDocument和IDOMDOCUMENT,使用IXMLDOCUMENT(使用它的方式几乎相同,然后TXmlDocument,但你不需要一个组件).
这段代码应该说明,它是多么简单:
{...} Var XML : IXMLDOCUMENT; RootNode,CurNode : IXMLNODE; begin XML := NewXMLDocument; XML.Encoding := 'utf-8'; XML.Options := [doNodeAutoIndent]; // looks better in Editor ;) RootNode := XML.AddChild('XML'); CurNode := RootNode.AddChild('Test'); CurNode := CurNode.AddChild('Test2'); CurNode.Text := 'Some Test 2 text'; CurNode.Attributes['NewAttribute'] := 'Some Test2 Attribute Value'; XMl.SaveToFile('C:\Documents and Settings\a\Desktop\zulfa.xml'); {...}
<?xml version="1.0" encoding="utf-8"?> <XML> <Test> <Test2 NewAttribute="Some Test2 Attribute Value">Some Test 2 text</Test2> </Test> </XML>
我希望这有帮助
PS:此示例仅需要XMLIntf和XmlDoc单元,以便您可以整理您的用途.