How to add an attribute to XML - c#

I am returning an object from a web service. It arrives in XML format -
<DailyTracker xmlns="http://schemas.datacontract.org/2004/07/MSI.Web.MSINet.BusinessEntities">
<ClientId>2147483647</ClientId>
<ClientRosterId>2147483647</ClientRosterId>
<Dept>
<DepartmentID>2147483647</DepartmentID>
<DepartmentName>String content</DepartmentName>
<EmailAddress>String content</EmailAddress>
<Location>2147483647</Location>
<PayCode>String content</PayCode>
</Dept>
etc, etc...
</DailyTracker>
This is coming from an asp.net website using c#. I am returning an object of type DailyTracker.
how can I add an attribute to one of the elements? Is that possible?
Thanks!

Instantiate an XDocument using the XML returned from the service. Get the XElement that you want, then add a new XAttribute to it:
XDocument document = new XDocument(xmlString);
XElement element = document.Element("myElement");
element.Add(new XAttribute("MyAttr", "My Value"));

You can override the Serialization process and add custom attributes to the Serialized XML content similar to the one that is described here

Related

Cannot convert XElement to XObject

I am trying to serialize an XML file using the following code:
XmlDocument xDoc = new XmlDocument();
xDoc.Load(#"D:\myfile.xml");
string jsonStr = JsonConvert.SerializeXNode(xDoc);
but it's not working and I am getting following error on 3rd line
Cannot convert XmlDocument into XObject
I also tried to find the first node and then try to pass it but its also not working.
You're using XmlDocument, which is from the "old" XML API. Json.NET uses the "new" XML API of LINQ to XML. You just need to change how you're loading the XML:
XDocument xml = XDocument.Load(#"D:\myfile.xml");
string json = JsonConvert.SerializeXNode(xml);

Can't load files that has xmlns attribute in the first child with XDocument

I am new to XDocument but I have been looking around for a solution to this problem which I couldn't get to fix.
I need to load some kind of XML files (PNML) that comes this way:
<pnml xmlns="http://www.pnml.org/version-2009/grammar/pnml">
<net id="id" type ="http://www.pnml.org/version-2009/grammar/ptnet">
..........</net> </pnml>
And I couldn't get to load these kind of files unless I add "xmlns" as an Attribute to the node net .
Meanwhile, the files I create myself has this xmlns attribute, and I can load them without problems.
While, files that are generated from some other software that I need to be able to use from my software doesn't has this "xmlns" attribute, and if I add it myself to the files generated by this software, I can load those files.
Here's the code I am using to Load :
XDocument doc = XDocument.Load(file);
XNamespace ns = #"http://www.pnml.org/version-2009/grammar/pnml";
foreach (XElement element in doc.Element(ns + "pnml")
.Elements("net").Elements("page").Elements("place"))
{ // Do my loading to "place" nodes for example }
But whenever I try to load a file, it just skips my "foreach" statement, and if I add some line before "foreach" like:
string id= (string) doc.Element(ns + "pnml")
.Element("net").Attribute("id");
it says:
Object reference not set to an instance of an object.
Here's an example of a file generated by my code and also can be read from my code:
<?xml version="1.0" encoding="utf-8"?>
<pnml xmlns="http://www.pnml.org/version-2009/grammar/pnml">
<net id="netid" type="http://www.pnml.org/version-2009/grammar/ptnet" xmlns="">
nodes and information </net> </pnml>
NOTE: I use this code to save my files:
XNamespace ns = #"http://www.pnml.org/version-2009/grammar/pnml";
XDocument doc = new XDocument
(
new XElement(ns+"pnml"
, new XElement("net",new XAttribute("id", net_id), ...));
I found a way to save my files without this "xmlns" attribute, but once I omit it, I can't load it from my code. And the first example I wrote is the standard format and I really need to get ride of the "xmlns" problem.
EDIT: I'm sorry if you got confused, what I want is to be able to load the standard PNML files that doesn't have thise "xmlns" attribute within the "net" node.
What you're missing is that element namespaces are inherited from their parents.
So your XML:
<pnml xmlns="http://www.pnml.org/version-2009/grammar/pnml">
<net id="id" type ="http://www.pnml.org/version-2009/grammar/ptnet">
...
Contains two elements. One is pnml with the namespace http://www.pnml.org/version-2009/grammar/pnml, and the child is net which also has the namespace http://www.pnml.org/version-2009/grammar/pnml.
With this in mind, your query on the existing XML should be:
doc.Element(ns + "pnml").Elements(ns + "net")...
And your code to generate the XML should be:
new XElement(ns + "pnml",
new XElement(ns + "net", new XAttribute("id", net_id), ...));
Try something like this
var result = doc.Element(ns + "pnml").Descendants().Where(x=>x.Name.LocalName=="net")

XDocument.Parse: Avoid replacing XXE references

I'm trying to protect against malicious XXE injections in the XMLs processed by my app. Therefore I'm using XDocument instead of XmlDocument.
The XML represents the payload of a web request so I call XDocument.Parse on its string content. However, I'm seeing the XXE references contained in the XML (&XXE) being replaced in the result with the actual value of ENTITY xxe.
Is it possible to parse the XML with XDocument without replacing &xxe ?
Thanks
EDIT:
I managed to avoid the replacement of xxes in the XML using XmlResolver=null for XDocument.Load
Instead of Parse try to use Load with a pre-configured reader:
var xdoc = XDocument.Load(new XmlTextReader(
new StringReader(xmlContent)) { EntityHandling = EntityHandling.ExpandCharEntities });
From MSDN:
When EntityHandling is set to ExpandCharEntities, the reader expands character entities and returns general entities as EntityReference nodes.
Use the following example to stop resolving XXE (schemas and DTD).
Dim objXmlReader As System.Xml.XmlTextReader = Nothing
objXmlReader = New System.Xml.XmlTextReader(_patternFilePath)
objXmlReader.XmlResolver = Nothing
patternDocument = XDocument.Load(objXmlReader)

How to create the XDocument instance for loading the XML file after deserializing the the object?

I am developing window phone 7 application. I am new to the window phone 7 application. I am referring to the following link for XML Serialization & Deserialization.
http://www.codeproject.com/KB/windows-phone-7/wp7rssreader.aspx
In the above link the LoadFromIso() function is used for XML Deserialization. I want to load the xml file after deserialization in the above link. In simple one case we can do this as in the following code. Similar to the following code I want "doc" in the above link. In the following code we can perform the various opeations on the XML file by using LINQ to XML with following statement
doc = XDocument.Load(isfStream);
The complete code is as follows
IsolatedStorageFile isfData = IsolatedStorageFile.GetUserStoreForApplication();
XDocument doc = null;
IsolatedStorageFileStream isfStream = null;
if (isfData.FileExists(strXMLFile))
{
isfStream = new IsolatedStorageFileStream(strXMLFile, FileMode.Open, isfData);
doc = XDocument.Load(isfStream);
isfStream.Close();
}
In the similar way I want the instance of the XDocument after deserializing the object so that I can perform the various operations on the XML file by using LINQ to XML. Can you please provide me any code or link through which I can obtain the instance of the XDocument so that I can load the XML file & perform the various operation on the XML file by using the LINQ to XML ?
The variable doc in your code is an XDocument of the deserialized content.
You can perform your operations on/with doc.
A simple WP7 project demonstrating loading XML using XDocument and LINQ and data binding to a listbox here. As Matt advises the work gets done on your XDocument instance.
binding a Linq datasource to a listbox

adding element to xml file from c#.net

how to add element to a xml file using asp.net& c#.net inweb application
Here's an example of adding a new element to the root node:
XDocument doc = XDocument.Load("test.xml");
doc.Root.Add(new XElement("someNode", "some node value"));
doc.Save("test.xml");
Load the document using XmlDocument class and then modify it as needed. Reference documentation and examples here.
You can use XmlDocument.CreateElement method to create it and then to append it

Categories

Resources