XML SelectSingleNode的使用 根据节点属性获取该节点

unit Unit1;

 

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, xmldom, XMLIntf, msxmldom, XMLDoc, msxml,StdCtrls;

type
  TForm1 = class(TForm)
    btn1: TButton;
    XMLDocument1: TXMLDocument;
    procedure btn1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.btn1Click(Sender: TObject);

var
  noderef: IXMLDOMNodeRef;
  root: IXMLDOMNode;
  Node: IXMLDOMNode;

begin
  XMLDocument1.LoadFromFile('test.xml');

  XMLDocument1.Active := True;
  noderef := XMLDocument1.DocumentElement.DOMNode as IXMLDOMNodeRef;
  root := noderef.GetXMLDOMNode; // 获取跟节点
  Node := root.selectSingleNode('ItemList/Item[@name="name2"]'); // 根据路径的属性值获取节点

  ShowMessage(Node.Attributes.getnameditem('title').Text); // title2

  Node.Attributes.getnameditem('title').Text:='hello'; // <Item name="name2" title="title2"/>  =>  <Item name="name2" title="hello"/> 
  XMLDocument1.SaveToFile('test.xml');
end;

end.

 

test.xml文档:

<?xml version="1.0" encoding="utf-8"?>
<Test>
    <ItemList>
        <Item name="name1" title="title1"></Item>
        <Item name="name2" title="title2"/>
    </ItemList>
</Test>

http://blog.csdn.net/henreash/article/details/16827007

posted @ 2016-03-17 01:55  findumars  Views(5056)  Comments(0Edit  收藏  举报