0

I have loaded an XML document into an XElement

It looks a little like this:

<my:myFields xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:my="http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-03-14T05:31:16" xmlns:xd="http://schemas.microsoft.com/office/infopath/2003" xml:lang="en-AU">
<my:header>
    <my:item1></my:item1>
    <my:item2></my:item2>
    <my:item3></my:item3>
</my:header>
<my:header2>
    <my:title1>Blah</my:title1>
    <my:title2>Zlib</my:title2>
    <my:title3>Bleep</my:title3>
</my:header2>

All I want to do, is search for the "node text" (i.e. "Blah", "Zlib" or "Bleep") given input "node name" (i.e. "title1", "title2", "title3")

I have tried xeData.Attribute("title1") and xeData.Element("title1") and also various linq statements without success.

How can I do this?

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
baron
  • 11,011
  • 20
  • 54
  • 88

2 Answers2

1

You need to consider the namespace of the "title" elements. Try this instead:

string titleText = xeData.Element(XName.Get("title1", "http://schemas.microsoft.com/office/infopath/2003/myXSD/2012-03-14T05:31:16")).Value;

I'm assuming here that xeData is the "header" element -- if it's not, you'll have to figure out how to select that first.

McGarnagle
  • 101,349
  • 31
  • 229
  • 260
1

If you want to find or create nodes in a namespace it helps using XNamespace objects which are part of the LINQ to XML. Here is an example:

    XElement myFields = XElement.Load("../../XMLFile3.xml");
    XNamespace my = myFields.GetNamespaceOfPrefix("my");
    Console.WriteLine(myFields.Element(my + "header2").Element(my + "title1").Value);

See also http://msdn.microsoft.com/en-us/library/bb387042.aspx.

Martin Honnen
  • 160,499
  • 6
  • 90
  • 110