Problem getting XML elements in an SVG file
I am trying to read a very basic SVG file which has the following contents:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="600" height="300" version="1.1" xmlns="http://www.w3.org/2000/svg">
<g stroke="black" >
<line x1="75" y1="160" x2="525" y2="160" stroke-width="10"/>
</g>
</svg>
I am trying to get a collection of line elements. However, the following code does not work:
XDocument XD = XDocument.Load(PathToFile);
XElement SVG_Element = XD.Root;
var adam = SVG_Element.Elements("line");
Upon inspecting the variables, the document is loaded properly, but the variable "adam" remains null, as if it does not find any elements with that name. Any help is appreciated.
Edit: Using De开发者_如何学Pythonscendants does not fix this. It still comes up empty.
Alright guys, I did figure this out. Apparently I need to specify the namespace as part of the QName:
var adam = SVG_Element.Descendants("{http://www.w3.org/2000/svg}line");
The line element is a grandchild of the root, not a child. Try the Descendants() method of the XDocument instead.
Try something like this:
Dim xmldoc As XDocument = XDocument.Load(Server.MapPath("PathtosvgFile"))
Dim Info As IEnumerable(Of XElement) = _
From typeElement In xmldoc.Descendants.Descendants
Where typeElement.Parent = "g"
Select typeElement
Dim tel As XElement
For Each tel In Info.DescendantsAndSelf.Distinct()
'Access each descendant here and do something.
Next
I never used XDocument to parse Xml files. I use XmlDocument. But I believe both work on a similar fashion. My guess is that you should first query for the "g" element, and then for the "line" element, something like the following:
XDocument XD = XDocument.Load(PathToFile);
XElement SVG_Element = XD.Root;
var gs = SVG_Element.Elements("g");
var adam = gs[0].Elements("line");
Hope it helps.
XDocument SVGDoc = XDocument.Load(yourfile);
XElement svg_Element = SVGDoc.Root;
IEnumerable<XElement> gElement = from e1 in svg_Element.Elements("{http://www.w3.org/2000/svg}g")
select e1;
int nCounter = 0;
foreach (XElement myElement in gElement)
{
...
}
精彩评论