I have an xml document that looks like this.
<?xml version="1.0" encoding="UTF-8"?>
<Job>
<ID>1</ID>
<Name>Front Window<Name>
<Image>/9j/4AAQSkZJRgABAQ..(etc)</windowImage>
</job>
<Job>
<ID>2</ID>
<Name>BackWindow<Name>
<Image>/9j/4BAQSkZJRgABAQ..(etc)</windowImage>
</job>
</xml>
Also a XSLT file which loops through each job. My problem is how can I insert the images which are saved as byte[]? They are only saved in the database and no file is created for them because they are generated in the application. My C# code looks like this.
Job jobClass = new ReportSQL().createXMLclass(_jobID);
new ReportSQL().createXMLFile(jobClass);
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(#"Code\quoteTemplate.xslt");
xslt.Transform("xmlfile.xml", "doc.doc");
I think the XML you want to produce saves the images as text. This can be accomplished by encoding the bytearray as Base64:
String s = Convert.ToBase64String(byte[])
and
byte[] b = Convert.FromBase64String(String)
Related
I've got to create a file with xml header and after that i have to put normal data, smthing like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Header>
<Algorithm>alg</Algorithm>
<nod2>aaa</nod2>
<nod3>bbb</nod3>
<node>
<User>
<Email />
<SessionKey />
</User>
</node>
</Header>
Data of the file....
I've already got the code to write it to the file.
Code for that part:
private void setHeader(FileStream output, string nod2, string nod3, string )
{
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", "yes");
doc.AppendChild(docNode);
XmlNode header = doc.CreateElement("Header");
doc.AppendChild(header);
XmlNode algorithm = doc.CreateElement("Algorithm");
algorithm.InnerText = "alg";
header.AppendChild(algorithm);
XmlNode node2= doc.CreateElement("nod2");
node2.InnerText = nod2;
header.AppendChild(node2);
XmlNode node3= doc.CreateElement("nod3");
node3.InnerText = nod3;
header.AppendChild(node3);
XmlNode node= doc.CreateElement("node");
header.AppendChild(node);
XmlNode user1 = doc.CreateElement("User");
node.AppendChild(user1);
XmlNode mail = doc.CreateElement("Email");
user1.AppendChild(mail);
XmlNode sessionKey = doc.CreateElement("SessionKey");
user1.AppendChild(sessionKey);
doc.Save(output);
}
It work's pretty well, but when i want to read it with
private void readHeader(FileStream input, out string algorithm)
{
XmlDocument doc = new XmlDocument();
doc.Load(input);
}
I got an error that when the "Data of the file..." starts: "Data on the root level is invalid".
Is there a way to do it with the data after whole xml, or have i to add the data as a node?
This can be done in multiple ways. In comments, you've indicated that the best way is unacceptable for reasons outside the scope of the discussion. For completeness, I'm going to put that one first anyway. Skip down to tl;dr for what I think you'll have to end up doing.
The preferred way to do this is to base64 encode the encrypted data and put it in a CDATA block:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<File>
<Header>
<Algorithm>alg</Algorithm>
<nod2>aaa</nod2>
<nod3>bbb</nod3>
<node>
<User>
<Email />
<SessionKey />
</User>
</node>
</Header>
<Data><![CDATA[
ICAgIFhtbE5vZGUgYWxnb3JpdGhtID0gZG9jLkNyZWF0ZUVsZW1lbnQoIkFsZ29yaXRobSIpOw0K
ICAgIGFsZ29yaXRobS5Jbm5lclRleHQgPSAiYWxnIjsNCiAgICBoZWFkZXIuQXBwZW5kQ2hpbGQo
YWxnb3JpdGhtKTsNCiAgICBYbWxOb2RlIG5vZGUyPSBkb2MuQ3JlYXRlRWxlbWVudCgibm9kMiIp
Ow0KICAgIG5vZGUyLklubmVyVGV4dCA9IG5vZDI7DQogICAgaGVhZGVyLkFwcGVuZENoaWxkKG5v
ZGUyKTsNCiAgICBYbWxOb2RlIG5vZGUzPSBkb2MuQ3JlYXRlRWxlbWVudCgibm9kMyIpOw0KICAg
IG5vZGUzLklubmVyVGV4dCA9IG5vZDM7DQogICAgaGVhZGVyLkFwcGVuZENoaWxkKG5vZGUzKTs=
]]></Data>
</File>
That's the canonical answer to this question.
But you've told me that in your case, a requirement has been imposed that you can't do it that way.
Second choice is MIME (actually, MIME might be the first choice and the above might be the second). But I have a feeling they won't like MIME either.
Third choice, read the file as a string and search for some marker that's inserted between the XML and the binary data, something like a MIME boundary.
tl;dr
If they won't let you add such a marker to the file (and I bet they won't), search for the first occurrence of the substring "</Header>":
var xml = File.ReadAllText(filePath);
var endTag = "</Header>";
var headerXML = xml.Substring(0, xml.IndexOf(endTag) + endTag.Length);
var xdHeader = new XmlDocument();
xdHeader.LoadXml(headerXML);
I tested your code with writing directly to a file, doc.Save(#"c:\temp\test1.xml");
And loading from that file works fine. So there is nothing wrong with your xml document. Check your FileStream. Do you flush and close it properly? Does it have UTF-8 encoding?
What's the input in the node strings. Nothing that is invalid according to xml rules?
After a single root node, only comments and processor instructions can be written to xml. So, you can try to write your data in the comments.
It will look like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Header>
...
</Header>
<!-- your data -->
<!-- another data -->
This method has limitations: your data may not contain -- (double-hyphen) and may not end in -.
But it is better, of course, not to do so.
I am trying to load an XML file that contains a mix of ASCII text and Arabic characters. Here is the top snippet:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="ar_EG">
<context>
<message>
<location filename="ui/aboutdialog.cpp" line="90"/>
<source>You have </source>
<translation type="unfinished">يوجد لديك</translation>
</message>
<message>
<location filename="ui/aboutdialog.cpp" line="90"/>
<source> launches left</source>
<translation type="unfinished">عدد التشغيلات المتبقية</translation>
</message>
</context>
I want to load this up into a C# TreeView object, but I am having issues with loading into XDocument or XMLDocument.
Using this:
XDocument xd = XDocument.Load(File.ReadAllText(tbxTSFileName.Text));
or
XDocument xd = XDocument.Load(File.ReadAllText(tbxTSFileName.Text, Encoding.GetEncoding(874)));
Gives me a "Invalid URI: Uri string is too long" error.
Using this:
XmlDocument xd = new XmlDocument();
xd.Load(tbxTSFileName.Text);
Gives the error "Invalid character in the given encoding. Line 9 position 40".
Read the documentation for the method you're calling.
XDocument.Load takes a URL, not an XML string.
You want XDocument.Parse.
Your reader needs to use utf-8, as indicated in the document itself. Ideally, you would use an XML reader and it would take care of using the indicated encoding itself.
I have following two xml strings
<?xml version="1.0"?>
<AccessRequest xml:lang='en-US'>
<AccessLicenseNumber>YOURACCESSLICENSENUMBER</AccessLicenseNumber>
<UserId>YOURUSERID</UserId>
<Password>YOURPASSWORD</Password>
</AccessRequest>
and
<?xml version="1.0" ?>
<RatingServiceSelectionRequest>
<PickupType>
<Code>01</Code>
</PickupType>
<Shipment>
<Description>Rate </Description>
<Shipper>
<Address>
<PostalCode>originzip</PostalCode>
</Address>
</Shipper>
<ShipTo>
<Address>
<PostalCode>destinationzip</PostalCode>
<CountryCode>countrycode</CountryCode>
</Address>
</ShipTo>
<Service>
<Code>11</Code>
</Service>
<Package>
<PackagingType>
<Code>02</Code>
<Description>Package</Description>
</PackagingType>
<Description>Rate Shopping</Description>
<PackageWeight>
<Weight>weight</Weight>
</PackageWeight>
</Package>
<ShipmentServiceOptions/>
</Shipment>
</RatingServiceSelectionRequest>
I want to append second xml string to first one. I tried writing both XmlDocuments to a XmlWriter. But it throws exception "Cannot write XML declaration. XML declaration can be only at the beginning of the document."
Stream stm = req.GetRequestStream();
XmlDocument doc1 = new XmlDocument();
XmlDocument doc2 = new XmlDocument();
doc1.LoadXml(xmlData1);
doc2.LoadXml(xmlData2);
XmlWriterSettings xws = new XmlWriterSettings();
xws.ConformanceLevel = ConformanceLevel.Fragment;
using (XmlWriter xw = XmlWriter.Create(stm, xws))
{
doc1.WriteTo(xw);
doc2.WriteTo(xw);
}
How can I append it as is? Please help
Remove <?xml version="1.0" ?> from second xml string before appending it to first xml string.
I had this problem in the past. The two lines of code below did the job:
var MyDoc = XDocument.Load("File1.xml");
MyDoc.Root.Add(XDocument.Load("File2.xml").Root.Elements());
If you already have strings ready, then please use the Parse function instead of Load.
Please notice I am using the System.Xml.Linq that uses XDocument instead of XmlDocument class.
EDIT
As I understood, you need both documents to be concatenated as is. The problem is that it will eventually leads to an invalid XML document for two reasons :
the document will contain two root nodes: AccessRequest and RatingServiceSelectionRequest. A valid XML document contains only one root node.
There must be only one <?xml version="1.0" ?> XML declaration at the beginning of a document.
If the UPS api your are using is fed with an invalid XML, you unfortunately can not use XML objects. Therefore you will have to use a simple string concatenation to achieve what you want:
var xml = xmlData1 + xmlData2;
My aim here is to convert the original xml file through some xsl to the destination having a utf-8 encoding. Here is the original xml file with the following header:
<?xml version='1.0' encoding='ISO-8859-1'?>
I'm transforming this using xsl to another xml file. The xsl file has the following header:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns="http://www.w3.org/1999/xhtml"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"
xmlns:xalan="http://xml.apache.org/xalan"
exclude-result-prefixes="xalan">
<xsl:output method="xml"
encoding="UTF-8"
indent="yes"
xalan:indent-amount="4"/>
Here is the C# code:
XPathDocument myXPathDoc = new XPathDocument(FileName);
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load("C:/test/test.xsl");
XmlTextWriter myWriter = new XmlTextWriter(destinationFile, Encoding.UTF8);
myWriter.Formatting = Formatting.Indented;
myWriter.Indentation = 4;
myXslTrans.Transform(myXPathDoc, null, myWriter);
myWriter.Close();
The output of this is I get a garbled arabic text at destinationfile. How do get this to read proper arabic text.
EDIT, Question 2:
The original XML file is missing the closing root/child tags. How do I edit this xml to include these in.
e.g. original xml file, missing closing for aaaa and nnnn. How do I edit using C# to get them in.
<aaaa>
<nnnn)
<rrrr>
</rrrr>
If your original XML file contains Arabic characters then its XML declaration is lying - the file is not encoding="ISO-8859-1" as that encoding cannot represent Arabic.
If you can determine what encoding the original file really uses you can force the file to be read in that encoding by using the XPathDocument constructor that takes a TextReader instead of the one that takes a file name. For Arabic, the encoding is probably Windows-1256.
I have some xml data contained in three files (Database.xml, Participants.xml, and ConditionTokens.xml). I am trying to use external entities to place the participants and condition tokens into the database file, but when I run this code...
string xmlPath = Environment.CurrentDirectory + #"\Data\Database.xml";
XElement database = XElement.Load(xmlPath);
...there are no participants or condition tokens in my xml (the HasElements property for "database" is false). There should be two child elements. I get no errors/warnings within Visual Studio (2008), and the live schema validation seems to be happy, but something is not quite right when I run my code.
Could anyone tell me what I'm doing wrong?
I have pasted the three xml files below.
Thanks very much!
-Dan
Database.xml
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE database [
<!ENTITY conditionTokens SYSTEM "ConditionTokens.xml">
<!ENTITY participants SYSTEM "Participants.xml">]>
<database
xmlns="experimentManager"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="experimentManager Database.xsd">
&conditionTokens;
&participants;
</database>
ConditionTokens.xml
<?xml version="1.0" encoding="utf-8" ?>
<conditionTokens>
<conditionToken>
<id>1</id>
<token>LargeToSmall</token>
</conditionToken>
<conditionToken>
<id>2</id>
<token>SmallToLarge</token>
</conditionToken>
</conditionTokens>
Participants.xml
<?xml version="1.0" encoding="utf-8" ?>
<participants>
<participant>
<id>1</id>
<conditionTokenId>1</conditionTokenId>
</participant>
<participant>
<id>2</id>
<conditionTokenId>2</conditionTokenId>
</participant>
</participants>
I would have used the XmlDocument class to load the 3 documents
XmlDocument xmlDatabase = new XmlDocument();
xmlDatabase.Load(databasePath);
XmlDocument xmlTokens = new XmlDocument();
xmlTokens.Load(tokensPath);
XmlDocument xmlParticipants = new XmlDocument();
xmlParticipants.Load(participantsPath);
Then using the ImportNode and AppendNode attach then to each other...
xmlDatabase.FirstChild.AppendNode(xmlDatabase.ImportNode(xmlTokens.FirstChild), true);
xmlDatabase.FirstChild.AppendNode(xmlDatabase.ImportNode(xmlParticipants.FirstChild), true);
That should pretty much do it (or instead of using FirstChild use an xpath selector?)
I ended up using <xs:redefine> instead.