Adding XML attribute to an element - c#

Looking to add an attribute to an existing xml element <D_COMMS>, not replace the existing attribute just add it to the beginning.
This is the XML
<OUTPUT version="2.0">
<RESPONSE>
<DATA id="17fb13cca6c5463597fdf340c044069f">
<![CDATA[<ID> jdfkldklfjdkl</ID><D_COMMS>ON this date...</D_COMMS>]]>
</DATA>
</RESPONSE>
This XML is the result of a HTTPWebResponse so this is what the XMl looks like when it comes back to me and I need to add a value to the D_COMMS element and send it back.Tried something like this to look for the descendant DATA and add it that way.
var addelement = doc.Descendants("DATA").First();
addelement.Add(XElement("D_COMMS","On this date we said"));

A better one to set attribute is in here Adding attributes to an XML node
XmlElement id = doc.CreateElement("id");
id.SetAttribute("userName", "Tushar");

You can find the DATA node and add an attribute as follows:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNodeList dataNodes = doc.GetElementsByTagName("DATA");
if (dataNodes != null && dataNodes.Count > 1)
{
dataNodes[0].Attributes.Append(doc.CreateAttribute("D_COMMS", "On this date we said"));
}

Related

Get childNode in childNode in XMLDocument

I have XML response from service and I need to get value of tag that exist in child node that this child node is a child node.
For example: This is an example of xml.
<ashrait>
<response>
<command>inquire</command>
<inquire>
<row>
<ResponseCode>000</ResponseCode>
<ResponseText>
Permitted.
</ResponseText>
<ResponseXML>
<ashrait>
<response>
<message>Permitted .</message>
<userMessage>Permitted .</userMessage>
</response>
</ashrait>
</ResponseXML>
</row>
</inquire>
</response>
</ashrait>
I need the the value in tag "userMessage" that exists in tag "ResponseXML".
I know that to get the node of "ResponseXML" I need for those lines:
var doc = new XmlDocument();
doc.LoadXml(responseFile);
ChildNode result = doc.GetElementsByTagName("ResponseXML")[0];
But how i get the tag userMessage in childNode "ResponseXML"?
Thanks
UPDATE:
I figured out how to do it.
Search for all the children with the tag and choose the order they want.
Create a model for your XML, load that model using XmlSerializer.
Check this Microsoft Docs.
https://learn.microsoft.com/en-us/dotnet/standard/serialization/examples-of-xml-serialization
Use
SelectNodes method: https://msdn.microsoft.com/en-us/library/hcebdtae(v=vs.110).aspx
or SelectSingleNode method: https://msdn.microsoft.com/en-us/library/system.xml.xmlnode.selectsinglenode(v=vs.110).aspx
var doc = new XmlDocument();
doc.LoadXml(Xml);
XmlNode xn = doc.SelectSingleNode("//ashrait//inquire//row//ResponseXML//message");
var innerText = xn.InnerText;

Get specific values from Xml

I don't how to extract the values from XML document, and am looking for some help as I'm new to C#
I am using XmlDocument and then XmlNodeList for fetching the particular XML document
Here is my code
XmlNodeList XMLList = doc.SelectNodes("/response/result/doc");
And my XML looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<result>
<doc>
<long name="LoadID">494</long>
<long name="EventID">5557</long>
<str name="XMLData"><TransactionDate>2014-05-28T14:17:31.2186777-06:00</TransactionDate><SubType>tblQM2222Components</SubType><IntegerValue title="ComponentID">11111</IntegerValue></str></doc>
<doc>
<long name="LoadID">774</long>
<long name="EventID">5558</long>
<str name="XMLData"><TransactionDate>2014-05-28T14:17:31.2186777-06:00</TransactionDate><SubType>tblQM2222Components</SubType><IntegerValue title="ComponentID">11111</IntegerValue></str></doc>
</result>
</response>
In this i have to fetch every the XMLData data that is under every doc tag and i have to fetch last doc tag EventID.
var xml = XDocument.Parse(xmlString);
var docs = xml.Root.Elements("doc");
var lastDocEventID = docs.Last()
.Elements("long")
.First(l => (string)l.Attribute("name") == "EventID")
.Value;
Console.WriteLine ("Last doc EventId: " +lastDocEventID);
foreach (var doc in docs)
{
Console.WriteLine (doc.Element("str").Element("TransactionDate").Value);
}
prints:
Last doc EventId: 5558
2014-05-28T14:17:31.2186777-06:00
2014-05-28T14:17:31.2186777-06:00
You can use two XPath expressions to select the nodes you want. To answer each part of your question in turn:
To select all of the XMLData nodes:
XmlNodeList XMLList
= doc.SelectNodes("/response/result/doc/str[#name='XMLData']");
To select the last EventId:
XmlNode lastEventIdNode =
doc.SelectSingleNode("/response/result/doc[position() =
last()]/long[#name='EventID']");
If not all doc nodes are guaranteed to have an event id child node, then you can simply:
XmlNodeList eventIdNodes =
doc.SelectNodes("/response/result/doc[long[#name='EventID']]");
XmlNode lastNode = eventIdNodes[eventIdNodes.Count - 1];
That should give you what you've asked for.
Update;
If you want the XML data inside each strXml element, you can use the InnerXml property:
XmlNodeList xmlList
= doc.SelectNodes("/response/result/doc/str[#name='XMLData']");
foreach(XmlNode xmlStrNode in xmlList)
{
string xmlInner = xmlStrNode.InnerXml;
}
There's one result tag short in your xml.
Try using this. It's cleaner too imho
XmlNodeList docs = doc.SelectSingleNode("response").SelectSingleNode("result").SelectNodes("doc");
Then you can use a combination of SelectSingleNode, InnerText, Value to get the data from each XmlNode in your list.
For example if you want the EventID from the first doc tag:
int eventID = int.Parse(docs[0].SelectSingleNode("long[#name='EventID']").InnerText);

Read first root node from XML

I work with three kinds of XML files :
Type A:
<?xml version="1.0" encoding="UTF-8"?>
<nfeProc versao="2.00" xmlns="http://www.portalfiscal.inf.br/nfe">
</nfeProc>
Tyepe B:
<?xml version="1.0" encoding="UTF-8"?>
<cancCTe xmlns="http://www.portalfiscal.inf.br/cte" versao="1.04">
</cancCTe>
Type C:]
<?xml version="1.0" encoding="UTF-8"?>
<cteProc xmlns="http://www.portalfiscal.inf.br/cte" versao="1.04">
</cteProc>
I have try with this code to read the first node :
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(#"C:\crruopto\135120068964590_v01.04-procCTe.xml");
XmlNodeList ml = xmlDoc.GetElementsByTagName("*");
XmlElement root = xmlDoc.DocumentElement;
exti = root.ToString();
but dont return anything i want to read the first node , need to know if the file is nfeProc ,canCTE or cteProc
The second question is how i get the value from "value" in the same tag???
Thanks
From this post:
//Root node is the DocumentElement property of XmlDocument
XmlElement root = xmlDoc.DocumentElement
//If you only have the node, you can get the root node by
XmlElement root = xmlNode.OwnerDocument.DocumentElement
I would suggest using XPath. Here's an example where I read in the XML content from a locally stored string and select whatever the first node under the root is:
XmlDocument doc = new XmlDocument();
doc.Load(new StringReader(xml));
XmlNode node = doc.SelectSingleNode("(/*)");
If you aren't required to use the XmlDocument stuff, then Linq is your friend.
XDocument doc = XDocument.Load(#"C:\crruopto\135120068964590_v01.04-procCTe.xml");
XElement first = doc.GetDescendants().FirstOrDefault();
if(first != null)
{
//first.Name will be either nfeProc, canCTE or cteProc.
}
Working with Linq to XML is the newest and most powerful way of working with XML in .NET and offers you a lot more power and flexibility than things like XmlDocument and XmlNode.
Getting the root node is very simple:
XDocument doc = XDocument.Load(#"C:\crruopto\135120068964590_v01.04-procCTe.xml");
Console.WriteLine(doc.Root.Name.ToString());
Once you have constructed an XDocument you don't need to use any LINQ querying or special checking. You simply pull the Root property from the XDocument.
Thanks i have solved this way the first part
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(nomear);
XmlNodeList ml = xmlDoc.GetElementsByTagName("*");
XmlNode primer = xmlDoc.DocumentElement;
exti = primer.Name;
First, to be clear, you're asking about the root element, not the root node.
You can use an XmlReader to avoid having to load large documents completely into memory. See my answer to a how to find the root element at https://stackoverflow.com/a/60642354/1307074.
Second, once the reader is referencing the element, you can use the reader's Name property to get the qualified tag name of the element. You can get the value as a string using the Value property.

Inserting XML Fragment after last specific node/element

I want to add an XML fragment to the last element to an XML document and I having problems i.e. the error I get is:
"The reference node is not a child of
this node".
So my existing XML document looks like this:
<MAP>
<LAYER name ="My first Layer">
<DATASET name="foo dataset" />
<SYMBOLOGY>
<SYMBOL colour="red" />
</SYMBOLOGY>
</LAYER>
<LAYER name="My second Layer">
<DATASET name="bar dataset" />
<SYMBOLOGY>
<SYMBOL colour="blue" />
</SYMBOLOGY>
</LAYER>
</MAP>
The XML fragment I want to insert after the last LAYER element is:
<LAYER name="My third Layer">
<DATASET name="whatever dataset" />
<SYMBOLOGY>
<SYMBOL colour="yellow" />
</SYMBOLOGY>
</LAYER>
The code I am using is:
XmlDocumentFragment xmlDocFrag = xmlDocument.CreateDocumentFragment();
xmlDocFrag.InnerXml = inputXML; //which is basically the third layer example - see above.
XmlElement rootElement = xmlDocument.DocumentElement;
XmlNode lastLayerNode = rootElement.SelectSingleNode(#"//LAYER[last()]");
rootElement.InsertAfter(xmlDocFrag, lastLayerNode); //error raised here.
Any ideas on what I'm doing wrong here would be much appreciated. My XPath query seems find and it seems to select the correct last layer it just won't insert after it for some bizarre reason.
UPDATE/SOLUTION - How to do this with XPATH
Finally figured it out in XPath - see the code below, I think it was down to basically not selecting the correct parent node in the first place, it's incorrect to select the last LAYER then try and InsertAfter() on this node. Better to select the level above i.e. MAP then AppendChild(). See below:
XmlDocumentFragment xmlDocFrag = xmlDocument.CreateDocumentFragment();
xmlDocFrag.InnerXml = inputXML;
XmlElement mapElement = (XmlElement)xmlDocument.SelectSingleNode(#"//MAP[last()]");
mapElement.AppendChild(xmlDocFrag);
Thanks to all the replies and help too :)
Taking into consideration that you need this to work with Framework 2.0, here's another solution:
string xml = "<map><layer>1</layer><layer>2</layer></map>";
string addMe = "<layer>3</layer>";
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
XmlDocumentFragment xmlDocFrag = xmlDocument.CreateDocumentFragment();
xmlDocFrag.InnerXml = addMe;
XmlElement rootElement = xmlDocument.DocumentElement;
rootElement.AppendChild(xmlDocFrag);
This results in:
<map><layer>1</layer><layer>2</layer><layer>3</layer></map>
Things look pretty good, but I would first try to avoid the xpath selection for the last node, and instead just use this:
rootElement.InsertAfter(xmlDocFrag, rootElement.LastChild);
I had similar issue, I used the ImportNode method to solve it
Here is a small example how you can use it to add node from different xml (stored in string) to your example at desired node in xml tree
string xmlstring =#"<tag>.....</tag>"; // holds xml tree to be appended
XmlDocument xml2 = new XmlDocument();
xml2.Load(#"path_of_main_xml");
XmlDocument xml1 = new XmlDocument();
xml1.Load(new StringReader(xmlString));
// get the node you want to import which in this icase is string
XmlNode elem = xml1.DocumentElement;
// use importNode to import it
XmlNode impnode = xml2.ImportNode(elem,true);
// get the node list of all node of particular tag name
XmlNodeList eNode = xml2.GetElementsByTagName("tag_name_of_parent");
eNode[0].AppendChild(impnode); // append new node
// write back the updates to same file
XmlWriter writer = XmlWriter.Create(#"path_of_main_xml");
xml2.Save(writer);

Retrieving attributes from XML

Why does running this code...
XmlDocument doc = new XmlDocument();
string xml = #"<?xml version=""1.0"" encoding=""utf-8"" ?>
<BaaBaa>
<BlackSheep HaveYouAny=""Wool"" />
</BaaBaa>";
doc.LoadXml(xml);
XmlNodeList nodes = doc.SelectNodes("//BaaBaa");
foreach (XmlElement element in nodes)
{
Console.WriteLine(element.InnerXml);
XmlAttributeCollection attributes = element.Attributes;
Console.WriteLine(attributes.Count);
}
Produce the following output in the command prompt?
<BlackSheep HaveYouAny="Wool" />
0
That is, shouldn't attributes.Count return 1?
When you call SelectNodes with "//BaaBaa" it returns all elements of "BaaBaa".
As you can see from your own document, BaaBaa has no attributes, it's the "BlackSheep" element that has the single attribute "HaveYouAny".
If you want to get the attribute count of child elements, you have to navigate to that from the node you are on when iterating through the nodes.
element.Attributes contains the attributes of the element itself, not its children.
Since the BaaBaa element doesn't have any attributes, it is empty.
The InnerXml property returns the XML of the element's contents, not of the element itself. Therefore, it does have an attribute.
<BlackSheep HaveYouAny=""Wool"" /> // innerXml that includes children
<BaaBaa> // is the only node Loaded, which has '0' attributes
solution
XmlAttributeCollection attributes = element.FirstChild.Attributes;
Will produce the following, required output
<BlackSheep HaveYouAny="Wool" />
1

Categories

Resources