How to read and write an XML File to identical copy


Hi Friend,

enjoy with this job who is copy an XML File identically and less you to create an document with your Ax specified record

static void ReadAndWriteIdenticalXMLFile(Args _args)
{
    //READ
    XmlDeclaration  Xmldeclaration;
    XMLDocument     doc;
    XMLNode         rootNode, XMLRead;
    XMLParseError   xmlError;
    str             XmlName;
    //WRITE
    XmlDocument     xmlDoc;
    XMLWriter       XMLWriter;
    XmlElement      AnyXmlNode,XMLWrite;

    void RecursiveXml(XMLNode _XMLRead,XmlElement _AnyXmlNode)
    {
        int             NumberElement, x, continuereading, i, NumberOfAttributes;  
        XmlAttribute    XmlAttributeRead;
        str             XmlNodeName;
        XmlElement      AnyXmlNodeInternal;
       
        NumberElement = _XMLRead.childNodes().length();
        for(x = 1;x<=NumberElement;x++)
        {
            if(x==1)
            {
                _XMLRead = _XMLRead.firstChild();
            }
            else
            {
                _XMLRead = _XMLRead.nextSibling();
            }

            XmlNodeName = _XMLRead.name();

            continuereading =_XMLRead.hasChildNodes();
            XMLWrite = xmlDoc.createElement(XmlNodeName);

            NumberOfAttributes = _XMLRead.attributes().length();
            for(i = 0;i<NumberOfAttributes;i++)
            {
                XmlAttributeRead = _XMLRead.attributes().item(i);
                XMLWrite.setAttribute(XmlAttributeRead.name(),XmlAttributeRead.nodeValue());
            }
            AnyXmlNodeInternal =_AnyXmlNode.appendChild(XMLWrite);

            if(continuereading && _XMLRead.childNodes().nextNode().name() != "#text")
            {
                RecursiveXml(_XMLRead,AnyXmlNodeInternal);
            }
            else
            {
                XMLWrite.innerText(_XMLRead.innerText());
            }
        }

        _XMLRead = _XMLRead.parentNode();
    }

    // Get the XML document
    doc = new XMLDocument();
    //doc.async(FALSE);
    doc.load(@"D:\\FileNameToRead.xml");
    xmlError = doc.parseError();

    if (xmlError && xmlError.errorCode() != 0)
    {
        print "Error: " + xmlError.reason();
        pause;
        return;
    }

    rootNode = doc.documentElement();

    xmlDoc = new XmlDocument();
    Xmldeclaration = xmlDoc.createXmlDeclaration("1.0","UTF-8","no");
    xmlDoc.insertBefore(Xmldeclaration,xmlDoc.documentElement());

    XmlName = doc.childNodes().nextNode().nextSibling().name();
    AnyXmlNode = xmlDoc.createElement(XmlName);
    XMLWrite = xmlDoc.appendChild(AnyXmlNode);

    XMLRead = rootNode.selectSingleNode("//"+XmlName);

    RecursiveXml(XMLRead,AnyXmlNode);

    XMLWriter = XMLWriter::newFile(@"D:\\FileNameToWrite.xml");
    xmlDoc.writeTo(XMLWriter);
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.