VC对于XML的解析以及操作
XML的查找
#include <stdio.h>
#include <iostream>
#import <msxml4.dll>
#include <string>
using namespace std;
void Travel(MSXML2::IXMLDOMNodePtr pDOMNode)
{
if (pDOMNode->GetnodeTypeString()==(_bstr_t)"element") // 获取节点类型
{
printf("%s: ", (char*)pDOMNode->GetnodeName()); // 获取节点标签名称
printf("%s ", (char*)(_bstr_t)pDOMNode->GetnodeTypedValue()); // 获取节点值
MSXML2::IXMLDOMNamedNodeMapPtr pDOMAttrList=pDOMNode->Getattributes(); // 获取节点属性列表
long nLen=pDOMAttrList->Getlength();
for (int j=0; j<nLen; j++)
{
MSXML2::IXMLDOMNodePtr pDOMAttr=pDOMAttrList->Getitem(j); // 获取指定属性
printf("%s=", (char*)pDOMAttr->GetnodeName()); // 获取属性名称
printf("%s", (char*)(_bstr_t)pDOMAttr->GetnodeTypedValue()); // 获取属性值
}
printf("\n");
// IXMLDOMNodeListPtr
//pDOMNode->GetchildNodes();
for (MSXML2::IXMLDOMNodePtr pDOMChild=pDOMNode->GetfirstChild()
; pDOMChild!=NULL
; pDOMChild=pDOMChild->GetnextSibling())
Travel(pDOMChild);
}
}
int main(int argc, char *argv[])
{
CoInitialize(NULL); // 初始化COM环境
// atexit(Exit);
MSXML2::IXMLDOMDocumentPtr pDOMDoc;
pDOMDoc.CreateInstance(__uuidof(MSXML2::DOMDocument40)); // 创建XMLDOMDocument对象
pDOMDoc->load("e:\\reg.xml"); // 加载XML文档
MSXML2::IXMLDOMNodeListPtr pDOMNodeList=pDOMDoc->getElementsByTagName("List"); // 根据标签获得节点列表
long nCnt=pDOMNodeList->Getlength();
for (int i=0; i<nCnt; i++)
{
MSXML2::IXMLDOMNodePtr pDOMNode=pDOMNodeList->Getitem(i); // 获取指定节点
//pDOMNodeList=pDOMNode->GetchildNodes();
//cout<<pDOMNodeList->Getlength();
Travel(pDOMNode);
相关文档:
C#序列化xml
关键步骤:
XmlSerializer xSerializer = new XmlSerializer(typeof(MyObj));
StringWriter sWriter = new StringWriter(CultureInfo.InvariantCulture);
XmlTextWriter xTextWriter = new XmlTextWriter(sWriter);
......
public string ConvertDataTableToXML(DataTable xmlDS)
{
MemoryStream stream = null;
XmlTextWriter writer = null;
try
{
stream = new MemoryStream();
writer = new XmlTextWriter(stream, Encoding.Default);
......
通常在操作xml的时候,都是通过inputstream(很多情况下是FileInputStream)来读入xml并转为dom的,很多人会遇到这种情况数据不是从文件读入的而是从String中取得的
于是会使用
InputStream in = new ByteArrayInputStream (str.getBytes());来取得inputstream ,但是这种InputStream中数据被转成了byte数组,所以转dom ......