Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Check if and add element to XML file
Message
From
18/05/2018 15:21:38
 
General information
Forum:
Visual FoxPro
Category:
Coding, syntax & commands
Miscellaneous
Thread ID:
01659959
Message ID:
01660125
Views:
45
>
>Sorry, Antonio. One more question, please.
>When I use your code the tag "/Setting" is placed (in the resulting xml file) right after the newly added element. Please see attached image. Do you know why and if I can change it? So that it would go to the end of the file?
>Thank you.

No problem, Dmitry.

Most probably, you don't need to. That is, normally it's quite irrelevant.

But in case if you really want to, you may create a text node with a line feed, and append it to the same ancestor (this is just a hack, to generalize a better and robust option would be to pretty-transform the whole document).

Here it goes, remade:
LOCAL Source AS String

* your source document (the contents of your "MyFile.xml")
TEXT TO m.Source NOSHOW
<?xml version="1.0" standalone="yes" ?>
<Setting>
	<MyElement1>123</MyElement1>
</Setting>
ENDTEXT

* what must exist in the document, and the initial value
LOCAL RequiredPath AS String
LOCAL DefaultContent AS String

m.RequiredPath = "/Setting/MyElement2"
m.DefaultContent = "dummy"

* our objects to access the DOM
LOCAL XML AS MSXML2.DOMDocument60
LOCAL Ancestor AS MSXML2.IXMLDOMNode
LOCAL NewElement AS MSXML2.IXMLDOMElement
LOCAL TextElement AS MSXML2.IXMLDOMText

m.XML = CREATEOBJECT("MSXML2.DOMDocument.6.0")
m.XML.Async = .F.
m.XML.LoadXML(m.Source)

* if the required path does not exist...
IF m.XML.Selectnodes(m.RequiredPath).length = 0
	* get what will be its ancestor
	m.Ancestor = m.XML.Selectnodes(LEFT(m.RequiredPath, RAT("/", m.RequiredPath) - 1)).item(0)
	* create a new element
	m.NewElement = m.XML.CreateElement(SUBSTR(m.RequiredPath, RAT("/", m.RequiredPath) + 1))
	* set its value
	m.NewElement.text = m.DefaultContent
	* and append it to the end of its parent
	m.Ancestor.appendChild(m.NewElement)
	* create a text element with a line feed
	m.TextElement = m.XML.Createtextnode(CHR(10))
	* and append to the ancestor, also
	m.Ancestor.appendChild(m.TextElement)
ENDIF

* the DOM is reconstructed...
MESSAGEBOX(m.XML.XML)
----------------------------------
António Tavares Lopes
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform