繁体   English   中英

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

[英]Get attribute value from the SVG (XML) root element

我已经使用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;
    }

返回“ M0,2491 2491,2491 2491,0 0,0 z”

第一条路径与视图框具有相同的坐标,因此这应该对我有用。

编辑:这行得通,但是在收到我最终选择的答案后,我调整了代码以配合该答案中的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM