A veces, solo necesitamos usar XML como algunas aplicaciones pequeñas, como simplemente guardar registros o algunas configuraciones. El cuadro Delphi tiene un archivo XML de lectura y escritura directa (ejemplos y código), y su función principal es las siguientes dos funciones (una lectura y una escritura):
{------------------------------------------------- ------------------------------ Diversión/Pro: getxmlnodeValue@fecha: 2004.12.11@param: xmlfilexml 文件 @param: xmlnodepath Nodo @param: XMLARATTRName Nombre del atributo en el nodo. @Param: el delimitador de los parámetros de la nodo DEP, predeterminado es.@Return: el valor del primer nodo ------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- } functetXmlNodeValue (strentityEngineFile: string; xmlnodePath: string; constXmlattrName: string = '' '; constdep: char ='. '): string; varxmlDocument: ixmlDocument; node: ixmlnode; xmlnodeList: tstrings; i: INTEGER; URLCOUNT: INTEGER; // ruta de nodo xml xmlnodeList: = tStringList.create; xmlnodeList.delimiter: = dep; xmlnodeList.delimitedText: = xmlnodePath; urlCount: = xmlnodeList.Count; // xml Object XMLDOCUNM (StrentityEngineFile); xmlDocument.active: = true; tryNode: = xMlDocument.DocumentElement; if (node.nodeName = xmlnodeList [0]) entoncesbegin // escaneos de nodo fori: = 1TourlCount-1DobEginif (nódico <> nide) (node.childnodes, xmlnodelist [i]) elsebreak; end; if (node = nil) thenbeginResult: = ''; endelseBegin // juzga si tomar atributos o contenido de nodo if (trim (xmlattrname) = '') entoncesResult: = node.TextelSeResult: = node.AttributeNodes.nodes [xmlattrname] .nodeValue; end; endelseBeginResult: = ''; end; Exceptresult: = 'Error'; End; xmlDocument.active: = false; end; {--- -------------------------------------------------- ------------------------------ Diversión/Pro: setXmlNodeValue@Fecha: 2004.12.11@param: xmlfilexml archivo@param: xmlnodepath node@param: el nombre del atributo en el nodo XMLATTRName. @Param: el delimitador de los parámetros de la noda DEP, predeterminado es.@Return: ninguna operación es exitosa --------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -------------------------------------------------- -----------------------------------------------} FunctionsetxmlNodeValue ( strentityEngineFile: string; xmlnodePath: string; constXMlattrName: string = '' '; constValue: string =' ''; constDep: char = ''. '): boolean; varxmlDocument: ixmlDocument; nodo: ixmlnode; xmlnodeList: tstrings; i: INteger; urlCountCount; : Entero; begin // xml nodo ruta xmlnodeList: = tStringList.create; xmlnodeList.delimiter: = dep; xmlnodeList.DelImitedText: = xmlnodePath; urlCount: = xmlnodeList.count; // xml Object XmlDocument: = txMLDOcument (nil) ; xmlDocument.LoadFromFile (StrentityEngineFile); xmlDocument.active: = true; TryNode: = xmlDocument.DocumentElement; if (node.nodeName = xmlnodeList [0]) entoncesbegin // escaneos nodo fori: = 1tourlCount-1doBeGinif (node <> nil) entoncesnode: = getNodeFromixMlnodeList (node.childNodes, xmlnodeList [i]) elsebreak; end; if (node <> nil) entoncesbeginif (trim (xmlattrName) = '' ') entoncesnode.text: = valueelSenode.tributenodes.nodes [xmlattrName] : = value; xmlDocument.Savetofile (StrentityEngineFile); End; End; Result: = True; Exceptresult: = false; end; xmlDocument.active: = false; end;Pero hay un problema con las dos funciones anteriores: solo puede encontrar el primer registro por nombre de nodo y nombre del atributo. Por ejemplo: si desea operar un archivo XML similar al siguiente, hay múltiples nodos y nombres de atributos con los mismos nombres de atributos, pero los valores de los atributos son diferentes, y las funciones de lectura y escritura anteriores continuarán huelga.
<Colourname = NormalAttributed = 100Green = 125Blue = 150/> <Colourname = GoodAttributed = 150Green = 175Blue = 200/> <Colourname = ExcelorTtributed = 0Green = 0blue = 255/>Ok, el mayor placer para los programadores es hacerlo usted mismo. Vamos a revisar estas dos funciones. Se agregan dos parámetros a la función original:
{------------------------------------------------- ----------------------------------------------- Fun/Pro : GetxmlNodeSpecialValue@fecha: 2004.12.11@param: xmlfilexml archivo@param: xmlnodepath nodo @param: xmlarattrname nombre del atributo en el nodo. @Param: el nombre del atributo en el nodo a buscar por xmlspecialname @param: xmlspecialValue El valor correspondiente a un cierto atributo en el nodo a buscar @param: el separador de parámetros del nodo Dep, predeterminado es. @Return: el valor de un cierto atributo --- -------------------------------------------- ------ -------------------------} FunctionGetXMLNodeSpecialValue (StrentityEngineFile: String; xmlNodePath: String; constxmlattrName: string = ''; constxmlSpecialName : String = ''; :=TStringList.Create ;xmlnodeList.Delimiter:=dep;xmlnodeList.DelimitedText:=xmlnodepath;urlcount:=xmlnodeList.Count;//xml object xmlDocument:=TXMLDocument.Create(nil);xmlDocument.LoadFromFile(strEntityEngineFile);xmlDocument. Activo: = true; [i]); node.attributeNodes.nodes [xmlspecialname] .nodeValue; // No quiero declarar una variable temporal aquí, por lo que uso el resultado para comparar, lo que puede ser peligros ocultos. while ((resultado <> xmlSpecialValue)) Dobeginnode: = node.nextsibling; end; resultado: = node.attributeNodes.nodes [xmlattrname] .nodeValue; end; end; end; endelseBeginResult: = ''; end; exceptresult: = 'error'; end; xmlDocument.active: = false; end;Escribir funciones
{------------------------------------------------- ----------------------------------------- Fun/Pro: setxmlnodespecialValue@fecha: 2004.12 .11@param: archivo xmlfilexml@param: xmlnodepath nodo @param: xmlarattrname nombre del atributo en el nodo. @Param: el nombre del atributo en el nodo a buscar por xmlspecialname @param: xmlSpecialValue El valor correspondiente a una propiedad en el nodo a buscar por @param: separador de parámetros de nodo DEP, predeterminado es. @Return: es la operación exitoso o no --- -------------------------------------------- ------ ------------------- : String = ''; ; CmpValue: string; begin // xml nodo ruta xmlnodeList: = tStringList.create; xmlnodeList.delimiter: = dep; xmlnodeList.deliMitedText: = xmlnodepath; urlCount: = xmlnodeList.count; // xml Object xmlDocument: = TCRETCUENT nil); xmlDocument.LoadFromFile (StrentityEngineFile); xmlDocument.active: = true; tryNode: = xmlDocument.DocumentElement; if (node.nodeName = xmlnodeList [0]) luegobegin // escane el nodo fori: = 1ToUrlCount-1doBeginif (node <>) nil) entoncesnode: = getNodeFromIMIXMLNodeList (node.childNodes, xmlnodeList [i]) elsebreak; end; if (node <> nil) entoncesbegin {if (trim (xmlattrname) = '' ') thennode.text: = valueelSenode.attributeNodes.nodes [ XMLATTRNAME] .NodeValue: = Value;} if (TRIM (XMLATTRNAME) = '') entonces entonces NextSibl; valor; end; xmlDocument.