2017-06-02 42 views
0
using System.Collections; 
using System.Collections.Generic; 
using UnityEngine; 
using System.Xml; 

public class XmlReader : MonoBehaviour 
{ 
    XmlDocument doc = new XmlDocument(); 

    // Use this for initialization 
    void Start() 
    { 
     doc.Load(@"C:\Users\myxml\Documents\mysvg.svg"); 
     XmlNode node = doc.DocumentElement.SelectSingleNode("/g"); 

     foreach (XmlNode nodes in doc.DocumentElement.ChildNodes) 
     { 
      string text = nodes.InnerText; //or loop through its children as well 
     } 
    } 

    // Update is called once per frame 
    void Update() 
    { 

    } 
} 

我想所有的孩子下<g>我該如何解析xml文件類型的svg?

然後給每個孩子解析到數組例如:

<g 
    inkscape:label="Layer 1" 
    inkscape:groupmode="layer" 
    id="layer1"> 
    <rect 
     style="opacity:1;fill:#00c8fc;fill-opacity:0.98823529;fill-rule:nonzero;stroke:none;stroke-width:1;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" 
     id="rect4155" 
     width="45.714287" 
     height="30" 
     x="37.387959" 
     y="115.30345" /> 
    <rect 
     style="opacity:1;fill:#00c8fc;fill-opacity:0.98823529;fill-rule:nonzero;stroke:none;stroke-width:1;stroke-linecap:round;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1" 
     id="rect4155-5" 
     width="45.714287" 
     height="30" 
     x="91.899246" 
     y="115.40621" /> 

所以我想創建數組稱之爲Rects 也許string[] Rects;

然後在數組中的每個Rect下將他的參數也作爲字符串:

Rect1 
fill:#00c8fc 
width="45.714287" 
height="30" 
x="37.387959" 
y="115.30345" 

這種格式。

於是我可以從另一個腳本訪問Rect1的和他的參數,如: Rect1.width ...或Rect1.x .... Rect1.fill ....

+0

不是svg html而不是xml? – jdweng

+0

答案是,你解析它與任何其他XML文件相同。這裏有幾十個類似的問題。 – miken32

+0

[我如何在C#中讀取和解析XML文件?](https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in -C) – miken32

回答

0

在這種情況下,而使用LINK to XML是方式靈活

XDocument xdoc = XDocument.Load(@"C:\Users\myxml\Documents\mysvg.svg"); 
var rectElements = xdoc.Descendants("rect"); 

foreach(var rect in rectElements){ 
    var attributes = rect.Attributes(); 
    //Store them in some sort of Data Structure to support your requirements, maybe a Dictionary 
}