我已经使用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");
在没有运气或得到任何回复之后,我通过使用以下方法成功地从第一个路径元素获得了我需要的值:
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;
}
返回“M0,2491 2491,2491 2491,0 0,0 z”
第一条路径与视图框具有相同的坐标,因此这应该对我有用。
编辑:这有效,但在收到我最终选择的答案后,我调整了我的代码以适应该答案中的方法。