GrzesiekO
GrzesiekO

Reputation: 1199

Xml with two attributes in C#

I want to make xml element like this:

<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</Atrybut>

Now I'm doing this in this way:

XmlNode xmlAtrybutNode = xmlDoc.CreateElement("ElementName ");

_xmlAttr = xmlDoc.CreateAttribute("Type");
_xmlAttr.Value = "FirstAttribute";
xmlAtrybutNode.Attributes.Append(_xmlAttr);

_xmlAttr = xmlDoc.CreateAttribute("Name");
_xmlAttr.Value = "SecondAttribute";
xmlAtrybutNode.Attributes.Append(_xmlAttr);


xmlAtrybutNode.InnerText = !string.IsNullOrEmpty(Value) 
    ? SetTextLength(Name, ValueLength) 
    : string.Empty;

Value is input variable in method. Is there possibility to make this in another way? More efficiently? Can I use xmlWriter? Now i'm using xmlDocument.

Upvotes: 3

Views: 4261

Answers (4)

Douglas
Douglas

Reputation: 54877

If you’re on .NET 3.5 (or later), you could use LINQ to XML. Make sure that the System.Xml.Linq assembly is referenced, and that you have a using directive for its eponymous namespace.

XDocument document = new XDocument(
    new XElement("ElementName",
        new XAttribute("Type", "FirstAttribute"),
        new XAttribute("Name", "SecondAttribute"),
        value));

If you subsequently want to write the XDocument to a target, you can use its Save method. For debugging, it’s useful to call its ToString method, which returns its XML representation as a string.

Edit: Replying to comment:

If you need to convert the XDocument created above into an XmlDocument instance, you may use code similar to the following:

XmlDocument xmlDocument = new XmlDocument();
using (XmlReader xmlReader = document.CreateReader())
    xmlDocument.Load(xmlReader);

Upvotes: 4

parapura rajkumar
parapura rajkumar

Reputation: 24403

You can use Linq to XML.

Basically

        XDocument doc = new XDocument();
        doc.Add(
            new XElement("ElementName", "Value",
                new XAttribute("Type", "FirstAttribute"),
                new XAttribute("Name", "SecondAttribute")));

will give this xml document

<ElementName Type="FirstAttribute" Name="SecondAttribute">Value</ElementName>

Upvotes: 6

Crab Bucket
Crab Bucket

Reputation: 6277

What about using LINQ to XML as in this article. That can be very elegant - it can all be done on one line.

 XDocument doc = new XDocument(
      new XDeclaration("1.0", "utf-8", "yes"),
      new XElement("element",
            new XAttribute("attribute1", "val1"),
            new XAttribute("attribute2", "val2"),
       )
);

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1062520

How about tweaking your existing code:

XmlElement el = xmlDoc.CreateElement("ElementName");
el.SetAttribute("Type", "FirstAttribute");
el.SetAttribute("Name", "SecondAttribute");
el.InnerText = ...;

Additional thoughts:

  • XElement
  • XmlSerializer (from a class instance)

Upvotes: 4

Related Questions