// Initialize the XML4C2 system.
   try
   {
       XMLPlatformUtils::Initialize();
   }

   catch(const XMLException& toCatch)
   {
       char *pMsg = XMLString::transcode(toCatch.getMessage());
       XERCES_STD_QUALIFIER cerr << "Error during Xerces-c Initialization.\n"
            << "  Exception message:"
            << pMsg;
       XMLString::release(&pMsg);
       return 1;
   }

1.  XML 생성하기  

DOMImplementation* impl =
  DOMImplementationRegistry::getDOMImplementation(X("Core"));

//(Root )노드 생성 
DOMDocument* doc = impl->createDocument(
         0,                    // root element namespace URI.
         X(”company”),   // root element name
         0);                   // document type object (DTD).

DOMElement* rootElem = doc->getDocumentElement();  

// node 생성와 값에 대한 값을 넣는다.
// 노드 생성
DOMElement*  prodElem = doc->createElement(X(”product”));
rootElem->appendChild(prodElem);

// 그 노드에 맞는 값
DOMText*    prodDataVal = doc->createTextNode(X(”Xerces-C”));
          prodElem->appendChild(prodDataVal);

2. 생성한 XML 파일로 저장하기.  

static XMLCh*  gOutputEncoding = 0;

DOMWriter  *theSerializer = ((DOMImplementationLS*)impl)->createDOMWriter();

// set user specified output encoding
theSerializer->setEncoding(gOutputEncoding);
XMLFormatTarget *myFormTarget;

myFormTarget = new LocalFileFormatTarget(”c://output.xml”);

theSerializer->writeNode(myFormTarget, *doc);  
3. 이미 생성된 XML 파일 검색하기  

// 이미 기본 설정한거라 보고…다운받으면 그 안에 소스가 존재합니다. 참고 바람.
// 외부 파일을 가져온다.
parser->resetDocumentPool();
doc = parser->parseURI(xmlFile);

// 파일을 검색할때는 재귀가 기본이다.

// DOMNode *n

if (n->getNodeType() == DOMNode::ELEMENT_NODE)

{

    // 노드의 이름 가져온다.
    char *name =  XMLString::transcode(n->getNodeName());

    // 노드에 대한 값을 가져온다.
    char* nodeValue = XMLString::transcode (n->getFirstChild()->getNodeValue ());

    // 속성
   if(n->hasAttributes()) {

        DOMNamedNodeMap *pAttributes = n->getAttributes();
        int nSize = pAttributes->getLength();

        // 한 노드에 붙어있는 모든 속성과 값을 가져온다.
        for(int i=0; nSize>i; i++){  
                   DOMAttr *pAttributeNode = (DOMAttr*) pAttributes->item(i);
                   // get attribute name
                   char *name = XMLString::transcode(pAttributeNode->getName());
                  
                   XERCES_STD_QUALIFIER cout << "Attribute Name : " << name << " -> “;
                   XMLString::release(&name);
                  
                   // get attribute type
                   name = XMLString::transcode(pAttributeNode->getValue());
                   XERCES_STD_QUALIFIER cout << “Attribute Value : “<< name << XERCES_STD_QUALIFIER endl;
                   XMLString::release(&name);
               }
   }
}



[출처 : http://www.soulfree.net/126]

+ Recent posts