I'm trying to get the contact number so have this Linq to XML
Dim x As XElement = Xelement.Load("E:\XMLFile1.xml")
Dim TopElements As IEnumerable(Of XElement) = Xelement.Elements
For Each Cs In TopElements
Dim c As String = Cs.Element("contact").Element("telnumber").Value
Next
This didnt work (even though i was under the customer node)
So i saw an example which gets it at TopElements so no need to have a For Each
Dim Contacts = From c In TopElements Where (c.Element("contact").Element("telnumber")) Select c
but again this returns null. How could i target the contact section only?
protected void Page_Load(object sender, EventArgs e)
{
XmlReaderSettings xs = new XmlReaderSettings();
xs.XmlResolver = null;
xs.ProhibitDtd = false;
XmlReader xr = XmlReader.Create(Server.MapPath("XMLFile1.xml"), xs);
XmlDocument doc = new XmlDocument();
doc.Load(xr);//载入源XML文件
XmlNamespaceManager nameSpace = new XmlNamespaceManager(doc.NameTable);
nameSpace.AddNamespace("abc","http://www.w3.org/TR/html4/");
XmlElement xmlFile = doc.DocumentElement;
var result =xmlFile.SelectNodes("abc:customer/abc:contact/abc:telnumber", nameSpace);
foreach (XmlElement xe in result)
{
Response.Write(xe.InnerText + "<br />");
}
}
Output:
Best regards
Cathy
MSDN Community Support
Please remember to click "Mark as Answer" the responses that resolved your issue.
If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.
Member
288 Points
1286 Posts
Get to node within XML using Linq to XML
Jan 29, 2018 01:07 PM|uid250511|LINK
My XML
I'm trying to get the contact number so have this Linq to XML
This didnt work (even though i was under the customer node)
So i saw an example which gets it at TopElements so no need to have a For Each
but again this returns null. How could i target the contact section only?
Star
8670 Points
2882 Posts
Re: Get to node within XML using Linq to XML
Jan 30, 2018 10:04 AM|Cathy Zou|LINK
Hi EssCee
Because this xml added xmlns namespace, so if we use SelectNodes, result will be null
Working code as below:
Xml:
Code:
Output:
Best regards
Cathy
Please remember to click "Mark as Answer" the responses that resolved your issue.
If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.