what's the easiest way to generate xml in c++?
Some may declare me an XML heretic - but one effective way is to just generate it with your favorite string output tools (print, output streams, etc) - this can go to a buffer or a file.
Once saved - you really should then validate with a schema before committing it our shipping it off.
For one of our projects we have a very simple set of templates for managing begin/end tags and attributes. These each have a stream output operator. This makes it very easy to generate the source XML and debug. This makes the structure of the XML generation code look very much like the XML itself.
One advantage of this is that you can generate large amounts of XML efficiently if streaming to a file. You will pay the validation costs later (presumably at a better time for an expensive operation).
The downside of this technique is that it is essentially output only. It is not suitable for creating then consuming XML dynamically.
How can I build XML in C#?
It depends on the scenario. XmlSerializer
is certainly one way and has the advantage of mapping directly to an object model. In .NET 3.5, XDocument
, etc. are also very friendly. If the size is very large, then XmlWriter
is your friend.
For an XDocument
example:
Console.WriteLine(
new XElement("Foo",
new XAttribute("Bar", "some & value"),
new XElement("Nested", "data")));
Or the same with XmlDocument
:
XmlDocument doc = new XmlDocument();
XmlElement el = (XmlElement)doc.AppendChild(doc.CreateElement("Foo"));
el.SetAttribute("Bar", "some & value");
el.AppendChild(doc.CreateElement("Nested")).InnerText = "data";
Console.WriteLine(doc.OuterXml);
If you are writing a large stream of data, then any of the DOM approaches (such as XmlDocument
/XDocument
, etc.) will quickly take a lot of memory. So if you are writing a 100 MB XML file from CSV, you might consider XmlWriter
; this is more primitive (a write-once firehose), but very efficient (imagine a big loop here):
XmlWriter writer = XmlWriter.Create(Console.Out);
writer.WriteStartElement("Foo");
writer.WriteAttributeString("Bar", "Some & value");
writer.WriteElementString("Nested", "data");
writer.WriteEndElement();
Finally, via XmlSerializer
:
[Serializable]
public class Foo
{
[XmlAttribute]
public string Bar { get; set; }
public string Nested { get; set; }
}
...
Foo foo = new Foo
{
Bar = "some & value",
Nested = "data"
};
new XmlSerializer(typeof(Foo)).Serialize(Console.Out, foo);
This is a nice model for mapping to classes, etc.; however, it might be overkill if you are doing something simple (or if the desired XML doesn't really have a direct correlation to the object model). Another issue with XmlSerializer
is that it doesn't like to serialize immutable types : everything must have a public getter and setter (unless you do it all yourself by implementing IXmlSerializable
, in which case you haven't gained much by using XmlSerializer
).
what's the best method to generate xml file
using XmlWriter
class in .Net
var writerSettings = new XmlWriterSettings();
writerSettings.Indent = true;
XmlWriter writer = XmlWriter.Create("d:\\MyFirstXmlFile.xml", writerSettings);
writer.WriteStartDocument();
writer.WriteStartElement("People");
writer.WriteStartElement("Person");
writer.WriteElementString("Name", "Zain Shaikh");
writer.WriteElementString("JobDescription", "Software Engineer");
writer.WriteElementString("Facebook", "http://www.facebook.com/zainshaikh");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
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 to create XML in C#
//Create XmlDocument
XmlDocument xmlDoc = new XmlDocument();
//Create the root element
XmlNode outputsElement = xmlDoc.CreateElement("outputs");
//Create the child element
XmlElement Element = xmlDoc.CreateElement("output");
//Create "name" Attribute
XmlAttribute nameAtt = xmlDoc.CreateAttribute("name");
Element.Attributes.Append(nameAtt);
//Create "value" Attribute
XmlAttribute valueAtt = xmlDoc.CreateAttribute("value");
Element.Attributes.Append(valueAtt);
//Create "type" Attribute
XmlAttribute typeAtt = xmlDoc.CreateAttribute("type");
Element.Attributes.Append(typeAtt);
//Append child element into root element
outputsElement.AppendChild(Element);
and to return it as string:
xmlDoc.OuterXml;
How to generate XML file dynamically using C on Linux platform?
well mostly i use mxml library in such condition but here you just want to make xml file dont want to parse that then you can directly make that xml file just like this way
#include<stdio.h>
struct my_data
{
int number;
char string[10];
};
void createdata(FILE *fb,struct my_data testData)
{
fprintf ( fb,"<Data>\n");
fprintf ( fb,"<number> %d </number>\n",testData.number);
fprintf ( fb,"<string> %s </string>\n",testData.string);
fprintf ( fb,"</Data>\n");
}
int main()
{
FILE *fb=fopen("test.xml","w");
struct my_data testData = {32,"Mr.32"};
fprintf ( fb,"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
createdata(fb,testData);
return 0;
}
this is just ruff code to help you to think... this code make belows xml file
−
<Data>
<number> 32 </number>
<string> Mr.32 </string>
</Data>
C# create simple xml file
You could use XDocument:
new XDocument(
new XElement("root",
new XElement("someNode", "someValue")
)
)
.Save("foo.xml");
If the file you want to create is very big and cannot fit into memory you might use XmlWriter.
How to generate an XML file with specific structure using C#?
Check the XElement
class: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/creating-xml-trees-linq-to-xml-2
The basic example is this:
XElement contacts =
new XElement("Contacts",
new XElement("Contact",
new XElement("Name", "Patrick Hines"),
new XElement("Phone", "206-555-0144"),
new XElement("Address",
new XElement("Street1", "123 Main St"),
new XElement("City", "Mercer Island"),
new XElement("State", "WA"),
new XElement("Postal", "68042")
)
)
);
Using the ToString() function on the XElement
object will return the value in string format.
To generate attributes like the id, you can use the XAttribute
class like this:
XElement phone = new XElement("Phone",
new XAttribute("Type", "Home"),
"555-555-5555");
Console.WriteLine(phone);
Best .net Method to create an XML Doc
Josh's answer shows how easy it is to create a single element in LINQ to XML... it doesn't show how it's also hugely easy to create multiple elements. Suppose you have a List<Order>
called orders
... you can create the whole document like this:
var xml = new XElement("Orders",
orders.Select(order =>
new XElement("Order",
new XAttribute("OrderNumber", order.OrderNumber),
new XElement("ItemNumber", order.ItemNumber),
new XElement("QTY", order.Quantity),
new XElement("Warehouse", order.Warehouse)
)
)
);
LINQ to XML makes constructing XML incredibly easy. It also has support for XML namespaces which is pretty easy too. For instance, if you wanted your elements to be in a particular namespace, you'd just need:
XNamespace ns = "http://your/namespace/here";
var xml = new XElement(ns + "Orders",
orders.Select(order =>
new XElement(ns + "Order",
... (rest of code as before)
LINQ to XML is the best XML API I've worked with... it's great for querying too.
Related Topics
Enum VS Constexpr for Actual Static Constants Inside Classes
Creating Library with Backward Compatible Abi That Uses Boost
What Is the Branch in the Destructor Reported by Gcov
Why Does This Simple Std::Thread Example Not Work
How to Check If a Function Exists in C/C++
Fastest Inline-Assembly Spinlock
C++ Read File Line by Line Then Split Each Line Using the Delimiter
Implicit Conversion When Overloading Operators for Template Classes
Why Is Operator!= Removed in C++20 for Many Standard Library Types
Finding Square Root Without Using Sqrt Function
How to Use Multiple Versions of Gcc
Why Do We Have Reinterpret_Cast in C++ When Two Chained Static_Cast Can Do Its Job
Fast Divisibility Tests (By 2,3,4,5,.., 16)
Problems with Running Exe File Built with Visual Studio on Another Computer
C++: How to Get Fprintf Results as a Std::String W/O Sprintf
How to Parallelize a for Loop Through a C++ Std::List Using Openmp