从SVG(XML)根元素获取属性值



我已经使用XML解析器成功地从SVG中的子元素中获取了属性值,但从同一SVG中获取视图框值时遇到了问题。

这是SVG的顶部。我试图从svg元素的viewBox属性中解析出"0 0 2491 2491":

<?xml version="1.0" encoding="utf-8" standalone="no"?>
<svg viewBox="0 0 2491 2491" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" stroke-linecap="round" stroke-linejoin="round" fill-rule="evenodd" xml:space="preserve">
<defs>
<clipPath id="clipId0">
<path d="M0,2491 2491,2491 2491,0 0,0 z" />
</clipPath>
</defs>
<g clip-path="url(#clipId0)" fill="none" stroke="rgb(100,100,100)" stroke-width="0.5" />

一些没有结果的示例代码:

//from calling method
xmlParser.GetAttributeValueAtSubElement("svg", "viewBox")
//class variables
private readonly XNamespace _NameSpace = "http://www.w3.org/2000/svg"; 
private readonly XNamespace _NameSpace_xlink = "http://www.w3.org/1999/xlink";  
//class constructor
public XMLParser(string filePath)
{
_FilePath = filePath;
_XML_Doc = XDocument.Load(_FilePath);
_XML_Elem = XElement.Load(_FilePath);
}
//attempt 1 failed
public string GetAttributeValueAtSubElement(string subElementName, string attributeName)
{
string rv = string.Empty;
IEnumerable<XAttribute> attribs =
from el in _XML_Elem.Descendants(_NameSpace + subElementName) 
select el.Attribute(attributeName);

foreach (XAttribute attrib in attribs)
{ rv = attrib.Value; }
return rv;
}
//attempt 2 failed
public string GetAttributeValueAtSubElement(string subElementName, string attributeName)
{
string rv = string.Empty;
IEnumerable<XAttribute> attribs =
from el in _XML_Elem.Elements(_NameSpace + subElementName) 
select el.Attribute(attributeName);
foreach (XAttribute attrib in attribs)
{ rv = attrib.Value; }
return rv;
}

简单。Viewbox不是子代,而是根。:

XDocument doc = XDocument.Load(FILENAME);
XElement svg = doc.Root;
string viewBox = (string)svg.Attribute("viewBox");

在这里没有任何运气或得到任何响应后,我通过使用成功地从第一个路径Element中获得了我需要的值

public string GetAttributeValueAtSubElement()
{
string rv = string.Empty;
IEnumerable<XAttribute> attribs =
from el in _XML_Elem.Descendants(_NameSpace + "path")  also?
select el.Attribute("d");
if (attribs.Count() > 0 && attribs.First<XAttribute>().Value.Contains("M0,")
&& attribs.First<XAttribute>().Value.Contains("z"))
rv = attribs.First<XAttribute>().Value; 
return rv;
}

返回"M02491 24912491 2491,0 0,0 z">

第一条路径与视图框的坐标相同,所以这对我来说应该有效

编辑:这很有效,但在收到我最终选择的答案后,我调整了我的代码,以符合该答案中的方法。

最新更新