• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

c++BuilderDelphiXML解析例子obj2XML

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

XMLDocument;

Xml.XMLIntf.hpp

Xml.XMLDoc.hpp

#include "Xml.Win.msxmldom.hpp"

 XMLDocument控件

Winapi.msxmlIntf.pas

selectsinglenode只返回一个结点
 SelectNodes返回多个匹配的结点

xml cdata

    vNode:=doc.CreateNode('abc',ntCData,'xxxx');

 

DOM解析器的3种选择

MSXML MS Windows/Omni

 

 

解析器的选择

Xml.XMLDoc.TXMLDocument.DOMVendor

http://docwiki.embarcadero.com/CodeExamples/Seattle/e/index.php?title=Category:C%2B%2B&pagefrom=SystemVarClear+%28C%2B%2B%29#mw-pages

void CreateDocument() {
    _di_IXMLDocument document = interface_cast<Xmlintf::IXMLDocument>
        (new TXMLDocument(NULL));
    document->Active = true;
 
    // Define document content.
    document->DocumentElement = document->CreateNode("ThisIsTheDocumentElement",
        ntElement, "");
    document->DocumentElement->Attributes["attrName"] = "attrValue";
    _di_IXMLNode nodeElement = document->DocumentElement->AddChild
        ("ThisElementHasText", -1);
    nodeElement->Text = "Inner text.";
    _di_IXMLNode nodeCData = document->CreateNode("any characters here",
        ntCData, "");
    document->DocumentElement->ChildNodes->Add(nodeCData);
    _di_IXMLNode nodeText = document->CreateNode("This is a text node.",
        ntText, "");
    document->DocumentElement->ChildNodes->Add(nodeText);
 
    document->SaveToFile(destPath);
}

 

生成文件

http://overblue.blogbus.com/logs/13954596.html

uses
  XMLDoc, XMLIntf;

{ 写入XML内容 }
var
  XMLDoc : TXMLDocument;
  Node1 : IXMLNode;
  Node2 : IXMLNode;
begin
  XMLDoc := TXMLDocument.Create(nil);
  try
    XMLDoc.Active := True;
    XMLDoc.Version := '1.0';
    XMLDoc.Encoding := 'GB2312';
    XMLDoc.Options := [doNodeAutoCreate,doNodeAutoIndent,doAttrNull,doAutoPrefix,doNamespaceDecl];

    XMLDoc.DocumentElement := XMLDoc.CreateNode('ReportObjectContent');
    Node1 := XMLDoc.DocumentElement;

    Node1 := Node1.AddChild('ReportObjectProperty');
    Node2 := Node1.AddChild('ReportName');
    Node2.SetAttributeNS('Value', '', ReportName);
    Node2 := Node1.AddChild('ReportType');
    Node2.SetAttributeNS('Value', '', ReportType);
    Node2 := Node1.AddChild('DataViewName');
    Node2.SetAttributeNS('Value', '', DataViewName);
    Node2 := Node1.AddChild('SQLStr');
    Node2.SetAttributeNS('Value', '', SQLStr);   

    XMLDoc.SaveToStream(Stream);
  finally
    XMLDoc.Free;
  end;

 

XMLDocument1.DOMDocument.childNodes['Config'].attributes['DataUpFlag'];

xml->DocumentElement->AddChild("TableClassName")->Text = aClassName;
xml->DocumentElement->AddChild("ApplicationName")->NodeValue = LabeledEdit5->Text;

  if (node->ChildNodes->Get(i)->NodeType() == ntElement)

读解析文件

LoadFromFile 

LoadXMLData 读XML字符串

DocumentElement
    _di_IXMLNode snode = XMLDocument1->DocumentElement->ChildNodes->Nodes("row");

__property _di_IXMLNode Nodes[System::OleVariant IndexOrName] = {read=GetNode/*, default*/};
    XMLDocument1->LoadFromFile(lxml);
    _di_IXMLNode snode = XMLDocument1->DocumentElement->ChildNodes->FindNode(aTableName);
    if (snode)
    {
        for (int i = 0; i < snode->ChildNodes->Count; i++)
        {
            _di_IXMLNode rownode = snode->ChildNodes->Get(i);

            String fn = rownode->Attributes["Field"];
        }

    }
    XMLDocument1->Active = false;

 

增加或修改节点

xml->CreateElement
xml->CreateNode

xml->DocumentElement->AddChild
    _di_IXMLNode nodeElement = xml->DocumentElement->ChildNodes->FindNode("DAOPath");
    if (nodeElement == NULL)
        nodeElement = xml->DocumentElement->AddChild("DAOPath");
    nodeElement->Text = DaoPath;

 

缩进,格式化

 XMLDocument1->Options = XMLDocument1->Options << doNodeAutoIndent;

<?xml version="1.0" encoding="utf-8"?>
<data>
  <config>
    <recent>aaa</recent>
  </config>
  <list>
    <row name="aa" port=""></row>
    <row name="bb"  port=""></row>
    </list>
</data>

 

读取recent的值

fangA = XMLDocument1->DocumentElement->ChildNodes->FindNode("config")->ChildNodes->FindNode("recent")->NodeValue;

 XMLDocument1->DocumentElement->ChildNodes->FindNode("config")->ChildNodes->FindNode("recent")->NodeValue="newstring";

 XmlDocument1.DocumentElement.ChildNodes[0];
Node := XmlDocument1.DocumentElement.ChildNodes[0]; // <Class> node
Node.ChildNodes.Add(LoadXMLData('<Property Name="Version" RttiType="tkString"></Property>').DocumentElement);
Node.ChildNodes.Add(LoadXMLData('<Property Name="ShowSubunit" RttiType="tkBoolean"></Property>').DocumentElement);
xml.DocumentElement.ChildNodes.FindNode('data').DOMNode.ownerDocument.importNode()


IDOMDocument
    xml.DOMDocument.appendChild()
    xml.DOMDocument.importNode()

  XMLDocument1.DocumentElement.ChildNodes.FindNode('').OwnerDocument.importNode//IXMLDocument没有此方法
  XMLDocument1.DocumentElement.ChildNodes.FindNode('').DOMNode.ownerDocument.importNode()//IDOMDocument有次方法
     node:= XMLDocument1.DocumentElement.ChildNodes.Nodes[i];
     node.ChildNodes.FindNode('nodename')

var
node:IXMLNode;

XMLDocument1.XML.Text;//包含version
XMLDocument1.DocumentElement.Xml//去掉 头描述version encoding 的xml
XMLDocument1.DocumentElement.Text


2、读取文件
LoadXMLDocument
Xml.XMLDoc
#include <Xml.XMLIntf.hpp>
IXMLDocument doc:=LoadXMLDocument('abc.xml');
_di_IXMLDocument doc=LoadXMLData("xmlstring");

_di_IXMLDocument doc=LoadXMLDocument("aa.xml");
doc->DocumentElement->ChildNodes->FindNode("jgbm")->NodeValue;
doc->DocumentElement->ChildNodes->FindNode("para")->Attributes["pw"];

官方的解释是会自动释放!这样就不用创建控件了。TXMLDocument
 http://docwiki.embarcadero.com/RADStudio/Berlin/en/XML_Support_Routines
http://docwiki.embarcadero.com/Libraries/Berlin/en/Xml.XMLDoc.LoadXMLDocument

Returns the interface for an XML document given the name of an XML file.

Call LoadXMLDocument to load an XML document from a file on disk and obtain its interface. LoadXMLDocument creates a new TXMLDocument object and uses it to parse the file specified by the FileName parameter. The TXMLDocument component is not given an owner, which means that it behaves like an interfaced object. When the application releases the interface that LoadXMLDocument returns, the TXMLDocument instance is automatically freed.

 
 Xml.Win.msxmldom, Xml.XMLDoc,Xml.xmldom,Xml.XMLIntf,Winapi.msxml,

selectSingleNode

 

procedure TForm4.Parxml( Sender : TObject );

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

  begin
    doc := LoadXMLDocument( 'test.xml' );
    noderef := doc.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"/>

  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 > 

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

 

ptNodes: IXMLDOMNode;

      pas:=  ptnodes.text;//读取节点值要用text,nodeValue取不到
        pName := ptNodes.nodeName;
        pas := ptNodes.nodeValue;//error null

 

解析C++builder工程文件

原始工程文件首行是<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

改成<Project>才能用selectSingleNode方法解析。

procedure TForm2.Button1Click(Sender: TObject);
var
  path: string;
  Xml: IXMLDocument;
  noderef: IXMLDOMNodeRef;
  Root: IXMLDOMNode;
  Node: IXMLDOMNode;
  ConditionStr: string;
  list: TStringList;
begin
  list := TStringList.Create;
  list.LoadFromFile('E:\test\tt.cbproj');
  list.Strings[0] := '<Project>';
  Xml := LoadXMLData(list.Text);
  noderef := Xml.DocumentElement.DOMNode as IXMLDOMNodeRef;
  Root := noderef.GetXMLDOMNode;
  path := 'PropertyGroup[@Condition="''$(Cfg_1_Win32)''!=''''"]/FinalOutputDir';
  Node := Root.selectSingleNode(path);
  if not Assigned(Node) then
    self.Caption := 'not not '
  else
    Caption := Node.nodeTypedValue;
  list.Free;
end;

 

C++builder

Winapi.msxmlIntf.hpp

Xml.Win.msxmldom.hpp

http://docwiki.embarcadero.com/Libraries/Berlin/en/Xml.Win.msxmldom.IXMLDOMNodeRef.GetXMLDOMNode

    _di_IXMLDOMDocument xdocm;

    _di_IXMLDOMNodeRef xdnodeRef;
    _di_IXMLDOMNode xdnode,xdnode2;    

 

 

    noderef := xml.DocumentElement.domnode as IXMLDOMNodeRef;
  root := noderef.GetXMLDOMNode;
   

   //c++读取属性节点

   xdnodeRef = XMLDocument1->DocumentElement->DOMNode;

  xdnode = xdnodeRef->GetXMLDOMNode();   

    xdnode->selectSingleNode(L"MakeItems/Item[@Name='teacher']", &xdnode2);

    BSTR name;
    xdnode2->get_nodeName(&name);

   this->Caption = name;

 

    xdnode->selectSingleNode

 

IXMLDOMDocument

 

_di_IDOMNode dnode;

 _di_IXMLDOMNodeList domNodeList;

    xdnode = dnode->firstChild;
//     dnode->hasChildNodes();

void Test_DOMVendor() {
    TXMLDocument *document;
    TDOMVendor *vendor;
 
    document = new TXMLDocument(NULL);
 
    // Get document vendor.
    vendor = document->DOMVendor;
    if (vendor != 0) {
        printf("Document DOM vendor is  \"%ls\".\n", vendor->Description());
    }
    else {
        printf("Document has no DOM vendor.\n");
    }
 
    // Display registered DOM vendors with this application.
    const int numVendors = DOMVendors->Count();
    printf("Number of registered DOM vendors with this application is %d.\n",
        numVendors);
    for (int i = 0; i < numVendors; i++) {
        vendor = DOMVendors->Vendors[i];
        printf("\t%ls\n", vendor->Description());
    }
 
    // Find a specific registered DOM vendor.
    vendor = DOMVendors->Find("MSXML");
    if (vendor != 0) {
        // Set document DOM vendor.
        document->DOMVendor = vendor;
        printf("Document DOM vendor is \"%ls\".\n",
            document->DOMVendor->Description());
    }
    else {
        printf("Could not find DOM vendor.\n");
    }
 
    delete document;
}

 遍历节点

  XmlNode: IXMLNode;
  XmlNodeList: IXMLNodeList

 

 XmlNodeList := Xml.DocumentElement.ChildNodes;

  XmlNode := XmlNodeList.First;
  while XmlNode <> nil do
  begin
    self.list_values.AddPair(XmlNode.NodeName, XmlNode.NodeValue);
    XmlNode := XmlNode.NextSibling;
  end;

 

保存文件

procedure TFrmPublicHealthMain.PNGButton1Click(Sender: TObject);
var
  pNode,cNode: IXMLNode; {定义两个节点: 父节点、子节点}
  astr:string;
  ms:TMemoryStream ;
  ss:TStringStream;
begin
  XMLDocument1.XML.Clear;
  XMLDocument1.Active := True;                {必须先激活}
  XMLDocument1.Version := '1.0';              {设置版本}
  XMLDocument1.Encoding := 'utf-8';          {设置语言}

  pNode := XMLDocument1.AddChild('科室名单'); {添加的第一个节点是根节点, 现在的 pNode 是根节点}
  pNode.SetAttribute('备注', '测试');         {为根节点设置属性}

  pNode := pNode.AddChild('人员');            {为根节点添加子节点, 现在的 pNode 是 "人员" 节点}
  pNode.SetAttribute('职务', '科长');         {设置属性}
  pNode.SetAttribute('备注', '正局级');

  cNode := pNode.AddChild('姓名');  {为 pNode 添加子节点, 返回值 cNode 指向了新添加的节点}
  cNode.Text := '张三';

  cNode := pNode.AddChild('性别');
  cNode.Text := '';

  cNode := pNode.AddChild('年龄');
  cNode.Text := '34';

  {查看}  //缺少  Encoding
  ShowMessage(XMLDocument1.XML.Text);

  {保存}
  XMLDocument1.SaveToFile('2.xml');
  XMLDocument1.SaveToXML(astr);
  self.mmoIn.Lines.Text := astr;

  //这样就有encoding了
  ms:= TMemoryStream.Create;
  XMLDocument1.SaveToStream(ms);
  ss := TStringStream.Create;
  ms.Position:=0;
  ss.CopyFrom(ms,ms.Size);
  self.mmoIn.Lines.Text := ss.DataString;
  ss.Free;
  ms.Free;

end;

 pNode.ChildValues['cfh'] := '023535325';

 

C#  XmlTextWriter

https://www.cnblogs.com/gc2013/p/4267636.html

// XmlTextWriter 写文件
            XmlTextWriter writeXml = new XmlTextWriter(@c:MyXml.xml,Encoding.UTF8);
            writeXml.WriteStartDocument(false);
            writeXml.WriteStartElement(NetWork);
  
            writeXml.WriteComment(网络配置信息);
            writeXml.WriteStartElement(configration);
  
            writeXml.WriteElementString(IpAddress,192.168.2.168);
            writeXml.WriteElementString(Netmask, 255.255.255.0);
            writeXml.WriteElementString(Gateway, 202.103.24.68);
  
            writeXml.WriteEndElement();
            writeXml.WriteEndElement();
  
            writeXml.Flush();
            writeXml.Close();

不用findNode的写法

 Xml.DocumentElement.ChildNodes['makeCard'].ChildNodes['sfzCard'].NodeValue

遍历节点

  self.XMLDocument1.LoadFromXML(Memo2.Lines.Text);
  for i := 0 to XMLDocument1.DocumentElement.ChildNodes.Count - 1 do
  begin
    self.Caption := XMLDocument1.DocumentElement.ChildNodes[i].NodeName;
    self.Caption := XMLDocument1.DocumentElement.ChildNodes[i].Text;
  end;

 

    for (int i = 0; i < XMLDocument1->DocumentElement->ChildNodes->Count; i++)
        {
 
            s1 = XMLDocument1->DocumentElement->ChildNodes->Get(i)->NodeName;
          s2=    XMLDocument1->DocumentElement->ChildNodes->Get(i)->Text;
}

 

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');

 

C# 保存时:
 dtXML.WriteXmlSchema("d://sampleSchema.xml");
 dtXML.WriteXml("d://sample.xml");
读取时:
 dtXML.ReadXmlSchema("d://sampleSchema.xml");
 dtXML.ReadXml("d://sample.xml");

 

DataSet dataSet = new DataSet();

DataTable dataTable = new DataTable();

dataSet.Tables.Add(dataTable);

dataSet.WriteXml("123.xml");

dataSet.ReadXml("123.xml");

DataTable dataTable = dataSet.Tables[0];

 


            DataTable dt = new DataTable();
            dt.ReadXmlSchema("aschema.xml");
            dt.ReadXml("testout.txt");

            DataView dv = dt.DefaultView;
            dv.RowFilter = "BKA265='未对应'";

            //1.过滤后直接获取DataTable
            DataTable newTable1 = dv.ToTable();

            this.dataGridView1.DataSource = newTable1;

 

 有了这个Schema,解析xml太牛了

xml数据文件,就直接到数据集了databable

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<data1>
    <row>
        <AKB020>0010023</AKB020>
        <AKC190>000000053628455</AKC190>
        <BKC037>1</BKC037>
        <AKC220>0</AKC220>
        <AAE073>0001218982</AAE073>
        <AAE072>00002</AAE072>
</row>
    <row>
        <AKB020>0010023</AKB020>
        <AKC190>000000053628455</AKC190>
        <BKC037>1</BKC037>
        <AKC220>0</AKC220>
        <AAE073>0001218982</AAE073>
        <AAE072>00002</AAE072>
</row>
XMLSchema
<?xml version="1.0" standalone="yes"?>
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
  <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="row" msdata:UseCurrentLocale="true">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="row">
          <xs:complexType>
            <xs:sequence>
                     <xs:element name="AKB020" type="xs:string" minOccurs="0" />
                     <xs:element name="AKC190" type="xs:string" minOccurs="0" />
                     <xs:element name="BKC037" type="xs:string" minOccurs="0" />
                     <xs:element name="AKC220" type="xs:string" minOccurs="0" />
                     <xs:element name="AAE073" type="xs:string" minOccurs="0" />
                     <xs:element name="AAE072" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

 

TNativeXml *DocXml = new TNativeXml(NULL);

DocXml->Root->NodeByName("sqldata")->NodeByName("Row")->NodeByName("prm_sysdate")->ValueUnicode;

c#写xml

 XmlTextWriter myXmlTextWriter = new XmlTextWriter(System.IO.Directory.GetCurrentDirectory()+@"\KPDZJKK.xml", null);
            //使用 Formatting 属性指定希望将 XML 设定为何种格式。 这样,子元素就可以通过使用 Indentation 和 IndentChar 属性来缩进。
            myXmlTextWriter.Formatting = Formatting.Indented;
            myXmlTextWriter.WriteStartDocument(false);
            myXmlTextWriter.WriteStartElement("bookstore");
            myXmlTextWriter.WriteStartElement("book");
            myXmlTextWriter.WriteAttributeString("paname", paname);
            myXmlTextWriter.WriteAttributeString("sfzh", sfzh);
            myXmlTextWriter.WriteAttributeString("phone", phone);
            myXmlTextWriter.WriteAttributeString("sex", sex);
            myXmlTextWriter.WriteAttributeString("mz", mz);
            myXmlTextWriter.WriteAttributeString("VUId", VUId);
            myXmlTextWriter.WriteEndElement();
            myXmlTextWriter.Flush();
            myXmlTextWriter.Close();

c#读取xml

            string ykt_in_xml;
            ykt_in_xml = System.IO.Directory.GetCurrentDirectory() + @"\KPDZJKK_YKT.xml";
XmlDocument doc = new XmlDocument();
            if (System.IO.File.Exists(ykt_in_xml))
            {
                doc.Load(ykt_in_xml);
                nametxtbox.Text = doc.SelectSingleNode("/bookstore/book").Attributes["paname"].Value;
                sextxtbox.Text = doc.SelectSingleNode("/bookstore/book").Attributes["sex"].Value;
                mztxtbox.Text = doc.SelectSingleNode("/bookstore/book").Attributes["mz"].Value;
                phonetxtbox.Text = doc.SelectSingleNode("/bookstore/book").Attributes["phone"].Value;
                codetxtbox.Text = doc.SelectSingleNode("/bookstore/book").Attributes["sfzh"].Value;

 

对象转换为XML,类转换为XML

智能是class,因为record不支持这种rtti的反射。record用json的序列化是支持的,没时间研究官方的序列化怎么做到支持record的;

TRttiField是字段,public里定义的就是字段能获取到。
TRttiProperty是属性,要在published里定义才能获取到。
不过这已经很方便了,对象转xml。
 function obj2xml(rootName:string;obj:TObject):string;
var
  xmldcoc: IXMLDocument;
  pNode: IXMLNode;
  t: TRttiType;
  // p: TRttiProperty;
  f: TRttiField;
  r: TValue;
begin
  t := TRttiContext.Create.GetType(obj.ClassType );
  xmldcoc := NewXMLDocument('');
  pNode := xmldcoc.AddChild(rootName);
  for f in t.GetFields do
    pNode.AddChild(f.name).Text := f.GetValue(obj).ToString;
  result := xmldcoc.Xml.Text;
end;

<request>
    <name>张飞</name>
    <age>28</age>
    <sex>男</sex>
</request>

调用代码

procedure TForm1.Button15Click(Sender: TObject);
var
obj:tperson;
begin
  obj := tperson.Create();
  obj.name := '张飞';
  obj.age := 28;
  obj.sex := '';
self.Memo1.Text:= obj2xml('request',obj);
obj.Free;
end;

  tperson = class
  public
    name: string;
    age: Integer;
    sex: string;
  end;

还有个办法 nativexml 的

ObjectSaveToXmlString

XML2ds

<?xml   version="1.0"   encoding="gb2312"?>
<!--文档版本信息,    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap