簡體   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