Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding XML attribute to an element

Tags:

c#

xml

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"));
like image 928
Jt2ouan Avatar asked Dec 26 '12 20:12

Jt2ouan


People also ask

What is XML attribute and element?

Attributes are part of XML elements. An element can have multiple unique attributes. Attribute gives more information about XML elements. To be more precise, they define properties of elements. An XML attribute is always a name-value pair.

How do you add an attribute to an existing XML element in Java?

Add a new attribute to the element, using setAttribute(String name, String value) . Call void prettyPrint(Document xml) method of the example. The method gets the xml Document and converts it into a formatted xml String, after transforming it with specific parameters, such as encoding.

Can XML tags have attributes?

XML elements can have attributes, just like HTML. Attributes are designed to contain data related to a specific element.

Can XML root element have attributes?

The root element of an XML message is based on an object structure and an operation specified for the channel or service used for the communication. The root element can contain one or more attributes. The following table shows the attributes that can apply to root elements.


1 Answers

A better one to set attribute is in here Adding attributes to an XML node

    XmlElement id = doc.CreateElement("id");
    id.SetAttribute("userName", "Tushar");
like image 119
FJ Chen Avatar answered Sep 21 '22 02:09

FJ Chen