XElement, XAttribute Default Values

R

Rory Becker

-------------------------------------------------------------
Dim x As String =
SomeXElement.<Element1>.<SubElement>[email protected]("So
meDefaultString")
-------------------------------------------------------------

It seems that the @SomeAttribute does not resolve to an XAttribute but to
a string which was unexpected.

So I guess I can Throw and Extension method on String and use that ?
 
M

Martin Honnen

Rory said:
Is there a way to do something like the following...

You could use If(@att, "default")
e.g. this sample

Dim foo As XElement = <foo>
<bar att="value"/>
<baz/>
</foo>
Dim val1 As String = If(foo.<bar>.@att, "default 1")
Dim val2 As String = If(foo.<baz>.@att, "default 2")
Console.WriteLine("val1: {0}; val2: {1}", val1, val2)

outputs

val1: value; val2: default 2
 
S

Steven Cheng [MSFT]

Hi Rory,

I agree with Martin that you can first get the value via LINQ expression,
and then use iif expression to check the value.


=========================
Dim xml As XElement = _
<foo><bar
attr1="value1">fdsfdsf<block>dfdsf</block></bar></foo>

Dim str1 As String = xml.<bar>[email protected]()
Console.WriteLine(IIf(String.IsNullOrEmpty(str1), "default value",
str1))
========================

Sincerely,

Steven Cheng

Microsoft MSDN Online Support Lead


Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.

==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

--------------------
 
R

Rory Becker

Hello Martin,
You could use If(@att, "default")
e.g. this sample
Dim foo As XElement = <foo>
<bar att="value"/>
<baz/>
</foo>
Dim val1 As String = If(foo.<bar>.@att, "default 1")
Dim val2 As String = If(foo.<baz>.@att, "default 2")
Console.WriteLine("val1: {0}; val2: {1}", val1, val2)
outputs

val1: value; val2: default 2

Sorry for the delayed reply.

Wow.... I had heard and indeed used the new If syntax ( with 3 params) to
replace iif but I had no Idea of the version with only 2 params.

Damn that's going to be useful.

Thanks very much
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top