English 中文(简体)
鉴于XElement - Find node text by node name
原标题:Given XElement - Find node text by node name

我已将XML文件装入<代码>。 XElement

看起来如此:

<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>

我想做的是,根据“姓名”(即“标题1”、“标题2”、“标题3”)的意见,寻找“正文”。

我尝试了<代码>xeData.Attribute(“标题1”)和xeData.Element(“职称1”)以及各种林克声明,但没有成功。

How can I do this?

问题回答

你们需要考虑“标题”要素的名称空间。 相反:

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

我在此假定,XeData是“头盔”因素——如果不是的话,你必须说明如何选择第一个单元。

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.





相关问题
Updating Linq to XML element values concatenation issues

I am trying to write a app.config / web.config error correcting app which will audit our developers applications for incorrect environment settings. I am using Linq to XML to accomplish this and I am ...

Is LINQ to XML s XElement ordered?

When I use LINQ to XML, is the order of the elements and attributes written out to text guaranteed to be the same order as how I added the XElement and XAttribute objects? Similarly, when I read in ...

热门标签