I have my XML file setup like this:
<Entry>
<Desired_due_date>date</Desired_due_date>
<Order_number>order</Order_number>
<Series_number>series</Series_number>
<Product_name>product</Product_name>
</Entry>
I want to add CDATA without dropping the tags f.e.:
<Product_name>[CDATA[Z19 7HW]]</Product_name>
Every solution I found either makes a new node which messes up my structure or drops the tags.
My code looks something like this:
writer.WriteComment("Results in XML format.");
writer.WriteStartElement("Entries");
writer.WriteElementString("Series_number", entries[i].Series_number);
writer.WriteElementString("End_date_2", entries[i].End_date2);
writer.WriteElementString("Norm", entries[i].Norm);
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
Do not use XmlWriter.WriteElementString. Instead:
writer.WriteStartElement("elementname");
writer.WriteCData("text that goes in CDATA section");
writer.WriteEndElement();
Related
I'm trying to create a SEPA XML with XmlWriter. The created XML has to look like this example:
http://www.ebics.de/fileadmin/unsecured/anlage3/anlage3_pain008/pain_ex/pain.008.003.02.xml
This is my code so far:
public void generateSepaXml()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create("C:\\Users\\Sybren\\Documents\\test.xml",settings))
{
String messageId = "Message ID";
writer.WriteStartDocument();
writer.WriteStartElement("Document"); //Document start
writer.WriteAttributeString("xsi",#"schemaLocation=""urn:iso:std:iso:20022:tech:xsd:pain.008.003.02 pain.008.003.02.xsd");
writer.WriteStartElement("CstmrDrctDbtInitn"); // CstmrDrctDbtInitn tag start
writer.WriteStartElement("GrpHdr"); //GrpHeader tag start
writer.WriteStartElement("MsgId",messageId); //Message tag start
writer.WriteEndElement(); //Message tag end
writer.WriteEndElement(); //GrpHdr end
writer.WriteEndElement(); //CstmrDrctDbtInitn tag end
writer.WriteEndElement(); //Document end
writer.WriteEndDocument();
}
}
The result of my code looks like this:
How can set the text in the Document tag the same to the Document tag in my example?
And for the message tag xmlns is added when I open the xml in IE. The xmlns tag isn't visible in the result image above (in Firefox). How to remove this tag? And how can I set the text in the MsgId the same to the MsgId in the linked example xml? Maybe XMLWriter isn't the best option in my case? If so what is another better option?
Ofcourse this is only a small part of the XML but if know how it works , I think I can do the rest myself.
Just a well-meant advise (since I have some experience in the area of financial data-exchange, especially with SEPA)... I would not try to implement that shit using such a low-level XML API; there´re better ways to create complex XML documents than assembling them piece-by-piece with XmlWriter.
Since SEPA documents can become quite big, achieving it the way you´re trying will probably result in unmaintainable and error-prone spaghetti code. Instead, I would recommend to investigate into a model-driven approach (one for each SEPA use-case to implement) and then use a generator (consider using an intermediate XML format that can be transformed using XSLT) or a text-processor to produce the final output...
I encountered following issue,
I first write to my xml file like this:
XmlTextWriter writer = new XmlTextWriter("course.xml", null);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("Course");
writer.WriteAttributeString("title", "Examle");
writer.WriteAttributeString("started", "true");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
And xml output I get is:
<?xml version="1.0"?>
<Course title="Example" started="true" />
After that I want to write more data to this xml file so I use my code again:
XmlTextWriter writer = new XmlTextWriter("course.xml", null);
writer.Formatting = Formatting.Indented;
writer.WriteStartDocument();
writer.WriteStartElement("Course");
writer.StartElement("Level");
writer.StartElement("Module");
writer.EndElement();
writer.EndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
And the xml output is:
<?xml version="1.0"?>
<Course>
<Level>
<Module>
</Module>
</Level>
</Course>
So it replaces my original data, and all attributes in the course tag. Therefore I need a way where it doesn't replace data, but instead add it inside existing tags.
XML files are just sequential text files. They are not a database or a random-access file. There is no way to just write into the middle of them.
I would recommend parsing the entire xml document into memory, adding the new data, and then writing the whole document back out again.
I have an xml file likes below.
<?xml version="1.0" encoding="utf-8" ?>
<Book>
<Title>Title</Title>
<Content>Content</Content>
</Book>
I want to write a new node after 'Content', I know how to use XMLDocument to do that, is there a way to use XMLTextWriter to do that?
You will have to write the whole Xml document, i.e. all elements and attributes and attribute values by using the XmlTextWriter. After you've written the <Content> element, you can write your additional element.
Something like this:
writer.WriteStartDocument();
writer.WriteStartElement("Book");
writer.WriteStartElement("Title");
writer.WriteString("Title");
writer.WriteEndElement();
writer.WriteStartElement("Content");
writer.WriteString("Content");
writer.WriteEndElement();
// insert your new data here
writer.WriteEndElement();
writer.WriteEndDocument();
<row>
<id>1</id>
<code></code>
<name></name>
<address></address>
<state></state>
<zone>?</zone>
</row>
<row>
<id>2</id>
<code>AA</code>
<name>Ataria</name>
<address>Sitapur National Highway 24, Uttar Pradesh</address>
<state>Uttar Pradesh</state>
<zone>NER</zone>
</row>
i have no root element in this xml file only row element start and end this xml file.
how Deserializing this type of data ? in c#
If you sure that missing root is only the one issue with your XML - just add it manually:
string fileContent = File.ReadAllText(path);
string rawXml = "<root>" + fileContent + "</root>";
// now you can use LINQ-to-XML or whatever
XDocument xdoc = XDocument.Load(rawXml);
You can also load an XML Fragment directly, via
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlReader reader = XmlReader.Create("tracelog.xml", settings))
{
while (reader.Read())
{
// Process each node of the fragment,
// possibly using reader.ReadSubtree()
}
}
You would create XElements by passing the results of reader.ReadSubTree() to XElement.Load(...).
Well to start with, it's not an XML file - or at least, it doesn't represent an XML document.
One option would be to copy the file into a new file which does have document start/end tags... then you can load it as a normal document. Just create a file, write a document start tag, copy the contents of this file, then write a document end tag, and close the file handle. You could even do this in memory.
Alternatively, it may be possible to read it as it is, in fragments - possibly via XmlReader. I can't say it's something I've done, and I'd generally encourage you to create a full XML file instead, as then you'll be on more familiar territory.
its not an XML file if it doesn't have the root. parser will throw an error if you try to parse it. you can do this way
<?xml version="1.0"?>
<Root>
--- add your file content here
</Root>
then give this file path to the parser.
I was advised to use XMLwriter to build HTML documents in order to display them in webbrowser object. Creating doctype and startelements like HTML,BODY is OK..but I am experiencing 2 main problems:
I cannot add tags like <br>. Using WriteString skips < and >.
The output string is one line - I would need something like writeLine. You know, when I display source its all in the first line.
Thanks
You could use the Indent property:
var settings = new XmlWriterSettings();
settings.Indent = true;
using (var writer = XmlWriter.Create(outputStream, settings))
{
writer.WriteDocType("html", "-//W3C//DTD XHTML 1.0 Transitional//EN", "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd", null);
writer.WriteStartElement("html");
writer.WriteStartElement("body");
writer.WriteStartElement("b");
writer.WriteValue("Test");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
}
HTML is not a valid XML format, as you are discoving with tags like <img ...>
You could create XHTML, which is XML compliant (specify this in your DOCTYPE)
In XHTML single tags are writen like this <br /> for example
HTML: <img src="..">
XHTML: <img src=".." />
This link might be helpful XHTML vs HTML
Whitespace layout is nice for humans to read, but makes no difference to how the browser renders the Xhtml. In fact stripping unnecessary whitespace will produce slightly smaller files.