I am trying to deserialize a XML file by using DataContractSerializer which containes node called "URL". Like this one:
<?xml version="1.0" encoding="utf-8"?>
<products>
<product ID="8717973147527">
<name>Something</name>
<price currency="EUR">9.00</price>
<URL>http://google.com</URL>
<images>
<image>http://google.com</image>
</images>
</product>
</products>
After deserialization property mapped to URL stays null. If I rename the xml node to "url" (lower case) or any other word it is working fine. The problem is that I am not able to change the XML, so I must find a way to deserialize it. Can anyone help me?
You can use the XmlAttribute to set the name as you expect it on the XML file as:
[Serializable]
public class ClassName
{
// Here set the Xml Name Attribute
[XmlAttribute("URL")]
string Url;
...
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 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;
Can any friends help on this.
Now I want to read a complete path when I get a value.
<?xml version="1.0" encoding="UTF-8" ?>
<Element xsi:schemaLocation="http://localhost/AML/CaseInvestigationMangement/Moduli/XmlImportControls/xsdBorrow.xsd xsd2009027_kor21.xsd" Kod="370" xmlns="http://localhost/AML/CaseInvestigationMangement/Moduli/XmlImportControls/xsdBorrow.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
/2001/XMLSchema-instance">
<ANode>
<BNode>
<CNode>
<Example>
<Name>John</Name>
<NO>001</NO>
</Example>
</CNode>
</BNode>
<ID>1234</ID>
<Date>2011-10-01</Date>
</ANode>
<ANode>
<BNode>
<CNode>
<Example>
<Name>Mike</Name>
<NO>002</NO>
</Example>
</CNode>
</BNode>
<ID>5678</ID>
<Date>2011-03-31</Date>
</ANode>
</Element>
Now I want to read a complete path when I get a value, like NO element then I want to store complete path NO->Example->Cnode->Bnode->Anode. please help...
I have used XMLTextReader to read xml element and value. for more reference please click I want to read the xml sub sub sub node name and value
With xml linq, you can do it as below:
var doc = XDocument.Load(#"fileUri");
var paths=doc.Descendants()
.Where(e=>!(e.HasElements || String.IsNullOrEmpty(e.Value)))
.Select(e=>e.Name+"->"+
String.Join("->",e.Ancestors().Select(a=>a.Name)));
I'm trying to get the value of the Address element from the following XML text, but it's not finding it unless I remove xmlns="http://www.foo.com" from the Root element. However, the XML is valid even with it. What's the problem here?
Since I'm getting the XML text from a web service, I don't have control over it, but I can strip out the xmlns part if I have to as the last resort.
<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.foo.com">
<Address>Main St SW</Address>
</Root>
var doc = XDocument.Parse(xmlTextAbove);
var address = doc.Descendants().Where(o => o.Name == "Address").FirstOrDefault();
Console.WriteLine(address.Value); // <-- error, address is null.
As your xml contains a namespace, you have to mention that in code. This will work:
XNamespace nsSys = "http://www.foo.com";
XElement xDoc = XElement.Load("1.xml");
XElement xEl2 = xDoc.Descendants(nsSys + "Address").FirstOrDefault();
However I had to change your xml a little bit, as it contained repeated xmlns:xsi and xmlns:xsd which should occur only once per xml format:
<?xml version="1.0" encoding="utf-8"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.foo.com" >
<Address>Main St SW</Address>
</Root>
Related article in MSDN: XNamespace Class
The document root's XML namespace is included in the textual representation of o.Name, which is actually an instance of XName so the condition never matches.
The easiest fix is to use LocalName for the comparison:
.Where(o => o.Name.LocalName == "Address")
I am novice and struggling in some XML operations Like open and Delete. I have done the Add part.
Partys.xml
<?xml version="1.0" encoding="utf-8"?>
<Partys>
<Customers>
<Customer CustomerID="1">
<PersonalName>
<LastName>Baker</LastName>
<FirstName>Eugene</FirstName>
</PersonalName>
<Citizenship>Africa</Citizenship>
</Customer>
<Customer CustomerID="2">
<PersonalName>
<LastName>Baker</LastName>
<FirstName>Eugene</FirstName>
</PersonalName>
<Citizenship>Africa</Citizenship>
</Customer>
</Customers>
</Partys>
Q: I want to open the node detail customer where CustomerID (Attribute) is 1. What is the C# code for this?
Q: I want to delete the node customer where CustomerID (Attribute) is 2. What is the C# code for this?
You could try something like this:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("Parties.xml");
XmlNode t = xmlDoc.SelectSingleNode("/Partys/Customers/Customer[#CustomerID='2']");
t.ParentNode.RemoveChild(t);
xmlDoc.Save();
Once you have t, you can do whatever you want with it including show it in the Console (by accessing the various properties)
Here, we have deleted the node and saved back to file, but you could do whatever you want with the XmlDocument....