我已经使用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;
}
答案 0 :(得分:1)
简单。 Viewbox不是后代,而是根。 :
XDocument doc = XDocument.Load(FILENAME);
XElement svg = doc.Root;
string viewBox = (string)svg.Attribute("viewBox");
答案 1 :(得分:0)
在这里没有任何运气或得到任何回应后,我成功使用以下方法从第一个路径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;
}
哪个返回“ M0,2491 2491,2491 2491,0 0,0 z”
第一个路径与视图框的坐标相同,因此这应该对我有用。
编辑:这行得通,但是在收到最终选择的答案后,我调整了代码以适应该答案中的方法。