I have an XML document:
<xsd:form-definition xmlns:xsd="http://...m.xsd"
xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="....xsd" ...>
<xsd:page>
<xsd:formant source-name="label" id="guid1" />
<xsd:formant source-name="label id="guid2" />
<xsd:formant source-name="label" id="guid3">
<xsd:value>2013-04-24</xsd:value>
</xsd:formant>
</xsd:page>
</xsd:form-definition>
and by C# code I want to iterate through the specific elements and get the id
attribute and value
(if exist) - lets say labels
.
To do so, I try the code
XDocument xml = (document load);
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
ns.AddNamespace("f", "http://m.xsd");
foreach (XElement e in xml.XPathSelectElements("//f:formant[@source-name = 'label']", ns))
{
....
}
but the foreach
loop does not return any elements. Why ?
It works for me. Check that your namespaces f
and xsd
match exactly. In your example they don't match. Also, there are some other syntax errors in your example, eg the source-name
value of the second formant
doesn't end with a double quote.
XDocument xml = XDocument.Parse(
@"<xsd:form-definition xmlns:xsd=""http://m.xsd""
xmlns:ds=""http://www.w3.org/2000/09/xmldsig#""
xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
<xsd:page>
<xsd:formant source-name=""label"" id=""guid1"" />
<xsd:formant source-name=""label2"" id=""guid2"" />
<xsd:formant source-name=""label"" id=""guid3"">
<xsd:value>2013-04-24</xsd:value>
</xsd:formant>
</xsd:page>
</xsd:form-definition>");
XmlNamespaceManager ns = new XmlNamespaceManager(new NameTable());
ns.AddNamespace("f", "http://m.xsd");
foreach (XElement e in xml.XPathSelectElements(
"//f:formant[@source-name = 'label']", ns))
{
Console.WriteLine(e);
}
Console.ReadLine();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.