Create new XML file and write data to it?
DOMDocument is a great choice. It's a module specifically designed for creating and manipulating XML documents. You can create a document from scratch, or open existing documents (or strings) and navigate and modify their structures.
$xml = new DOMDocument();
$xml_album = $xml->createElement("Album");
$xml_track = $xml->createElement("Track");
$xml_album->appendChild( $xml_track );
$xml->appendChild( $xml_album );
$xml->save("/tmp/test.xml");
To re-open and write:
$xml = new DOMDocument();
$xml->load('/tmp/test.xml');
$nodes = $xml->getElementsByTagName('Album') ;
if ($nodes->length > 0) {
//insert some stuff using appendChild()
}
//re-save
$xml->save("/tmp/test.xml");
Java creating a new xml file and appending it
I simulated your code here and did realized the you are not creating a valid root element in XML file, that's why you getting the exception.
See my results that I am getting running the write method:
public static void main(String... x) {
Sentence s = new Sentence();
Main m = new Main();
List<Sentence> list = new ArrayList<Sentence>();
list.add(s);
m.write(list);
}
Sentence class:
public class Sentence {
public String[] getWordList() {
return new String[] { "w4", "w5", "w6" }; // previous: w1,w2,w3
}
}
file.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<text>
<sentence>
<word>w1</word>
<word>w2</word>
<word>w3</word>
</sentence>
<sentence>
<word>w4</word>
<word>w5</word>
<word>w6</word>
</sentence>
<sentence>
<word>w4</word>
<word>w5</word>
<word>w6</word>
</sentence>
</text>
Solution:
Just replace your code with the following:
// text element
Element rootElement = null;
if (!fileExist) {
rootElement = doc.createElement("text");
doc.appendChild(rootElement);
} else {
rootElement = doc.getDocumentElement(); // get the root [text] element
}
Create write and save xml file dynamically in c# .net
Two thing:
- Please post correct code. The XDocument class has no instance method
"parse", only "Parse". The XDocument class has no instance method
"Load", only static method "Load". - xdoc.Parse(content) would create
a XDocument from the string. XDocument.Load(filename) would return a
XDocument loaded from the XML file "filename".
This would do the job:
foreach(DataRow dr in dt.Rows) {
string filepath = ConfigurationManager.Appsetings[Constants.FailedDocuments];
string filename = "message_"+ dr["documentId"].ToString();
string content = dr["documentContent"].ToString();
XDocument xdoc = new XDocument();
xdoc.Parse(content);
xdoc.Save(filepath+filename);
}
Write an XML file through a C program
The problem appears to be in your function call:
output(f,m);
This way, for each iteration, you're essentially accessing the first element m[0]
in the function call.
You want to pass the address of each individual elements in the array, like
output(f,&(m[i]));
or, to simplify, you can pass the element itself (not the address), like
output(f,m[i]);
and change the function like
void output(FILE *f, Measurement x){ // second argument is not a pointer
fprintf(f,"<day>\n");
fprintf(f,"<minimum>%f</minimum>\n",x.minimum); // x is not a pointer
fprintf(f,"<maximum>%f</maximum>\n",x.maximum); .....
That said, the scan statements
scanf("%f",&x->daynumber);
should be
scanf("%d",&x->daynumber);
as daynumber
is of type int
, and for the others
scanf("%f",&x->minimum);
should be
scanf("%lf",&x->minimum);
as minimum
and other members are of type double
.
How do I create individual XML files from the parsed data output of a XML file?
Just use the File I/O APIs as usual to create your xml files within the loop.
// for every Node in the template List
for(int i=0; i < templateList.getLength(); i++) {
// cast each Node to a template Element
Node theTemplate = templateList.item(i);
Element templateElement = (Element) theTemplate;
// get the xml filename as = template's name attribute + .xml
String fileName = templateElement.getAttribute("name") + ".xml";
// create a Path that points to the current directory
Path filePath = Paths.get(fileName);
// create the xml file at the specified Path
Files.createFile(filePath);
System.out.println("File "+ fileName + ".xml created");
}
The above code would create the xml files in your current working directory. You'll need to handle the checked IOException
too.
Generate XML document in R
Might be easily solveable w/out any of those packages... if your structure is fairly static, I would use https://github.com/tidyverse/glue and then just cat()
the file out. Something like this:
## I guess your data looks like this?
df <- data.frame(number = c(1,2),
uri = c("S1A_IW_GRDH_1SDV_20190818T175529_20190818T175554_028627_033D25_22ED.zip<",
"S2A_MSIL1C_20190823T061631_N0208_R034_T42TXS_20190823T081730.zip"),
plugin = c("class org.esa.s1tbx.io.sentinel1.Sentinel1ProductReaderPlugIn",
"class org.esa.s2tbx.dataio.s2.ortho.plugins.Sentinel2L1CProduct_Multi_UTM42N_ReaderPlugIn"))
df
## build a function that outputs every block in xml format
thingieBuilder <- function(number, uri, plugin){
glue::glue("<product>
<refNo>{number}</refNo>
<uri>{uri}</uri>
<productReaderPlugin>{plugin}</productReaderPlugin>
</product>")
}
## now run that for each entry in your df and unlist it, and make it a sausage, seperated by newlines
xmlProducts <- df %>% purrr::pmap(thingieBuilder) %>% unlist %>% paste(collapse = "\n")
## Now stick on top and bottom, and cat it to a file!
glue::glue("<session>
<modelVersion>1.0.0</modelVersion>
<products>\n",
xmlProducts,
"/n</products>
<views/>
</session>") %>%
cat(file = "boom.xml")
How to create XML file using Python?
You need to
- Use
ET.tostring()
to get your xml as a string - Use
xml.dom.minidom
to get a DOM object from the string - Use
toprettyxml()
of DOM object to get the xml as formatted string - Add encoding information to the xml declaration part by simply splitting and concating the formatted string
- Write the string to a file
Code:
import xml.etree.cElementTree as ET
import xml.dom.minidom
m_encoding = 'UTF-8'
root = ET.Element("data")
doc = ET.SubElement(root, "status", date="20210123")
ET.SubElement(doc, "name", name="john").text = "some value1"
ET.SubElement(doc, "class", name="abc").text = "some vlaue2"
dom = xml.dom.minidom.parseString(ET.tostring(root))
xml_string = dom.toprettyxml()
part1, part2 = xml_string.split('?>')
with open("FILE.xml", 'w') as xfile:
xfile.write(part1 + 'encoding=\"{}\"?>\n'.format(m_encoding) + part2)
xfile.close()
Output file
<?xml version="1.0" encoding="UTF-8"?>
<data>
<status date="20210123">
<name name="john">some value1</name>
<class name="abc">some vlaue2</class>
</status>
</data>
Related Topics
Converting an Array from One to Multi-Dimensional Based on Parent Id Values
Are PHP Associative Arrays Ordered
Cast the Current Object ($This) to a Descendent Class
How to Count Same Values in an Array and Store It to a Variable
Fatal Error: Call to Undefined Method MySQLi_Result::Fetch_All()
PHP Foreach by Reference Causes Weird Glitch When Going Through Array of Objects
How to Find Number of Mondays or Tuesdays Between Two Dates
(Mysql, PHP) How to Get Auto_Increment Field Value Before Inserting Data
Vim Inoremap for Specific Filetypes
Woocommerce: Set Country by Default in Checkout Page
Warning: MySQL_Result() Expects Parameter 1 to Be Resource, Boolean Given
Unexpected T_Encapsed_And_Whitespace, Expecting T_String or T_Variable or T_Num_String Error