Click here to Skip to main content
15,879,326 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am writing a new sub to writer to an XML document, but I need to know how to add and attribute to a certain Xelement
VB
Dim xdoc As XDocument = Nothing
            Dim xEle As XElement = Nothing
            Dim xNode As XElement = Nothing

            'create new document
            xdoc = New XDocument
            'add root
            xEle = New XElement("CurrentJobs")
            xdoc.Add(xEle)
            'add jobs
            For Each job As JobBoard In Jobs
                xNode = New XElement("Job")
                xNode.Add(New XElement("CustomerName", job.JobName))
                xNode.Add(New XElement("PurchaseOrder", job.JobName))
                xEle.Add(xNode)
            Next
            xdoc.Save(jFileName)


I am adding the attribute
XML
status="a-current"
to the 'Job' tag. so the output looks like...
XML
<?xml version="1.0" encoding="utf-8"?>
<CurrentJobs>
	<Job status="a-current">
		<CustomerName>St Michael</CustomerName>
		<PurchaseOrder></PurchaseOrder>
	</Job
Posted

This is how: http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.setattributevalue%28v=vs.110%29.aspx[^].

However, are you sure that you really need to deal with XML level? Many people doing that could do it without direct use of XML, using serialization.

—SA
 
Share this answer
 
Comments
Matt T Heffron 12-Jan-15 16:44pm    
+5 (simultaneous solutions...)
Sergey Alexandrovich Kryukov 12-Jan-15 16:47pm    
Thank you, Matt.
—SA
You mean like:
VB
xNode.Add(New XAttribute("status", "a-current"))
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 12-Jan-15 16:47pm    
I see. 5ed.
—SA
Sean Donnahoe 13-Jan-15 8:14am    
I figured it might be that easy.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900