Как предотвратить исключение C# неверного броска при анализе данных XML, которые содержат комментарииC#

Место общения программистов C#
Ответить
Anonymous
 Как предотвратить исключение C# неверного броска при анализе данных XML, которые содержат комментарии

Сообщение Anonymous »

У меня есть следующий кодовый блок C#, который анализирует XML DOM в графический интерфейс для игры, которую я разрабатываю: < /p>
public void ReadChildrenOf(XmlElement element, GameObject parent)
{
foreach (XmlNode mchild in element.ChildNodes)
{
if (mchild.NodeType == XmlNodeType.Comment)
continue;
if (mchild.NodeType == XmlNodeType.Element)
{
XmlElement child = mchild as XmlElement;
if(child != null)
{
string id = "null";
float x = 0, y = 0;
float w = 0, h = 0;
Vector2 anchorMax = new Vector2(0, 0);
Vector2 anchorMin = new Vector2(0, 0);
bool receivesUpdates = false;

if (child.HasAttribute("x"))
x = float.Parse(child.GetAttribute("x"));
if (child.HasAttribute("y"))
y = float.Parse(child.GetAttribute("y"));
if (child.HasAttribute("w"))
w = float.Parse(child.GetAttribute("w"));
if (child.HasAttribute("h"))
h = float.Parse(child.GetAttribute("h"));
if (child.HasAttribute("id"))
id = child.GetAttribute("id");
if (child.HasAttribute("receivesUpdates"))
receivesUpdates = bool.Parse(child.GetAttribute("receivesUpdates"));
if (child.HasAttribute("anchorMin"))
{
string[] anchorMinStr = child.GetAttribute("anchorMin").Trim().Trim('(', ')').Split(',');
anchorMin = new Vector2(float.Parse(anchorMinStr[0]), float.Parse(anchorMinStr[1]));
}
if (child.HasAttribute("anchorMax"))
{
string[] anchorMaxStr = child.GetAttribute("anchorMax").Trim().Trim('(', ')').Split(',');
anchorMax = new Vector2(float.Parse(anchorMaxStr[0]), float.Parse(anchorMaxStr[1]));
}

GameObject childObj = null;
Debug.Log("Button" == child.Name);

switch (child.Name)
{
case "Button":
if (buttonPrefab != null)
{
childObj = Instantiate(buttonPrefab, new Vector3(x, y, 0), Quaternion.identity, parent.transform);
//childObj.GetComponent().OnParsed(child, this, scriptContext);
childObj.GetComponent().anchoredPosition = new Vector2(x, y);
}
break;
case "Text":
if (textPrefab != null)
{
childObj = Instantiate(textPrefab, new Vector3(x, y, 0), Quaternion.identity, parent.transform);
childObj.GetComponent().anchoredPosition = new Vector2(x, y);
}
break;
case "Image":
if (imagePrefab != null)
{
childObj = Instantiate(imagePrefab, new Vector3(x, y, 0), Quaternion.identity, parent.transform);
childObj.GetComponent().anchoredPosition = new Vector2(x, y);
}
break;
case "TextButton":
if (textButtonPrefab != null)
{
childObj = Instantiate(textButtonPrefab, new Vector3(x, y, 0), Quaternion.identity, parent.transform);
childObj.GetComponent().anchoredPosition = new Vector2(x, y);
}
break;
case "TextField":
if (textFieldPrefab != null)
{
childObj = Instantiate(textFieldPrefab, new Vector3(x, y, 0), Quaternion.identity, parent.transform);
childObj.GetComponent().anchoredPosition = new Vector2(x, y);
}
break;
case "HorizontalLayout":
if (textFieldPrefab != null)
{
childObj = Instantiate(horizontalLayoutGroupPrefab, new Vector3(x, y, 0), Quaternion.identity, parent.transform);
childObj.GetComponent().anchoredPosition = new Vector2(x, y);
LayoutRebuilder.ForceRebuildLayoutImmediate(parent.GetComponent());
}
break;
case "VerticalLayout":
if (textFieldPrefab != null)
{
childObj = Instantiate(verticalLayoutGroupPrefab, new Vector3(x, y, 0), Quaternion.identity, parent.transform);
childObj.GetComponent().anchoredPosition = new Vector2(x, y);
LayoutRebuilder.ForceRebuildLayoutImmediate(parent.GetComponent());
}
break;
case "GridLayout":
if (textFieldPrefab != null)
{
childObj = Instantiate(horizontalLayoutGroupPrefab, new Vector3(x, y, 0), Quaternion.identity, parent.transform);
childObj.GetComponent().anchoredPosition = new Vector2(x, y);
LayoutRebuilder.ForceRebuildLayoutImmediate(parent.GetComponent());
}
break;
case "Script":
if (scriptObjectPrefab != null)
{
childObj = Instantiate(scriptObjectPrefab, new Vector3(x, y, 0), Quaternion.identity, parent.transform);
childObj.GetComponent().anchoredPosition = new Vector2(x, y);
}
break;
case "ScrollView":
if (scrollViewPrefab != null)
{
childObj = Instantiate(scrollViewPrefab, new Vector3(x, y, 0), Quaternion.identity, parent.transform);
childObj.GetComponent().anchoredPosition = new Vector2(x, y);
}
break;
case "Content":
//Content is a special element that is used inside a ScrollView. It is not instantiated directly.
//We're adding all children in the content to the parent scrollview's content object.
childObj = parent.GetComponent().GetContent();
break;
default:
bool foundPrefab = false;
for (int i = 0; i < customPrefabs.Length; i++)
{
if ((child.Name + "Prefab") == customPrefabs.name)
{
childObj = Instantiate(customPrefabs, new Vector3(x, y, 0), Quaternion.identity, parent.transform);
childObj.GetComponent().anchoredPosition = new Vector2(x, y);
foundPrefab = true;
break;
}
}
if (!foundPrefab)
Debug.LogError("[XmlCanvas] Unknown XML element type: " + child.Name);
break;
}

if (childObj == null)
{
Debug.LogError("[XmlCanvas] Could not create child object of type " + child.Name);
return;
}
else
{
//childObj.name = id;
if (id != "null")
{
childObj.name = id;
if (childElementsByID.ContainsKey(id))
{
Debug.LogError("[XmlCanvas] Duplicate ID found: " + id);
}
else
{
if (childObj.GetComponent() == null)
childObj.AddComponent();
Debug.Log("[XmlCanvas.ReadChildrenOf]" + " Element with ID " + id + " is being added.");
childElementsByID.Add(id, childObj.GetComponent());
}
children.Add(childObj.GetComponent());
}
if (child.HasAttribute("x") || child.HasAttribute("y"))
childObj.GetComponent().anchoredPosition = new Vector2(x, y);
else
childObj.GetComponent().anchoredPosition = new Vector2(0, 0);
if (child.HasAttribute("w") || child.HasAttribute("h"))
childObj.GetComponent().sizeDelta = new Vector2(w, h);
if (child.HasAttribute("anchorMin"))
childObj.GetComponent().anchorMin = anchorMin;
if (child.HasAttribute("anchorMax"))
childObj.GetComponent().anchorMax = anchorMax;
if (childObj.GetComponent() != null)
{
childObj.GetComponent().OnParsed(child, this, scriptContext);
}
else
{
Debug.Log("[XmlCanvas] Child object does not have a ScriptableXmlGUIElement component. Adding one.");
childObj.AddComponent();
childObj.GetComponent().OnParsed(child, this, scriptContext);
}
}
}
}
}
}
< /code>
Данные, анализируемые в настоящее время (ради более быстрой отладки этого вопроса): < /p>














< /code>
Когда присутствует комментарий, документ не проанализируется из -за «неверного исключения изделия».InvalidCastException: Specified cast is not valid.
Moddable.GUI.XmlCanvas.ReadChildrenOf (System.Xml.XmlElement element, UnityEngine.GameObject parent) (at Assets/Source/GUI/Moddable.GUI/ModdableGUI_Source/XmlCanvas.cs:140)
Moddable.GUI.XmlCanvas.LoadDocument () (at Assets/Source/GUI/Moddable.GUI/ModdableGUI_Source/XmlCanvas.cs:120)
GUIDocumentManager.Awake () (at Assets/Source/GUI/Moddable.GUI/ModdableGUI_Source/GUIDocumentManager.cs:28)
< /code>
Это xmlcanvas.loaddocument: < /p>
public void LoadDocument()
{
//this.customPrefabs = new Dictionary();
UserData.RegisterType();
UserData.RegisterAssembly();
if (fileType == FileSystemType.STREAMING_ASSETS)
{
//Debug.Log("[XmlCanvas] Loading XML document from path: " + xmlDocumentPath);
//xmlDocumentPath = System.IO.Path.Combine(Application.streamingAssetsPath, xmlDocumentPath);
//Debug.Log("[XmlCanvas] Application.streamingAssetsPath: " + Application.streamingAssetsPath);
//Debug.Log("[XmlCanvas] Full XML document path: " + xmlDocumentPath);
this.xmlDocument = new XmlDocument();
xmlDocument.Load(Application.streamingAssetsPath + xmlDocumentPath);

scriptContext = new Script();
scriptContext.Options.DebugPrint = (s) => Debug.Log(s);
scriptContext.Options.ScriptLoader = new MoonSharp.Interpreter.Loaders.FileSystemScriptLoader();
//scriptContext.DoFile(System.IO.Path.Combine(Application.streamingAssetsPath, luaScriptFilePath));
}
else
{
Debug.LogError("[XmlCanvas] Loading XML and Lua from a text asset is not yet supported.");
}
if (this.canvas == null)
this.canvas = GetComponent();

GameObject root = Instantiate(rootPrefab, canvas.transform);
root.name = "Root";
//root.GetComponent().SetParent(this.canvas.transform);
//root.GetComponent().anchoredPosition = this.canvas.GetComponent().position;*/
root.GetComponent().anchorMin = new Vector2(0, 0);
root.GetComponent().anchorMax = new Vector2(1, 1);
this.root = root;
ReadChildrenOf(xmlDocument.DocumentElement, root);
}
< /code>
И это gudocumentmanager.awake (): < /p>
void Awake()
{
foreach(string documentFile in DocumentList)
{
//PrefabDocument.GetComponent().xmlDocumentPath = documentFile;
XmlCanvas newDocument = Instantiate(PrefabDocument, this.transform);
newDocument.gameObject.name = "[Document]" + Path.GetFileNameWithoutExtension(documentFile);
xmlDocuments.Add(Path.GetFileNameWithoutExtension(documentFile), newDocument);
newDocument.xmlDocumentPath = Path.Combine(Application.streamingAssetsPath, documentFile);
newDocument.LoadDocument();
newDocument.gameObject.SetActive(false);
}
this.defaultDocument = DocumentList[0];
this.SetActiveDocument(Path.GetFileNameWithoutExtension(this.defaultDocument));
}
< /code>
Я не могу на протяжении всей жизни выяснить, где происходит актерский состав, не говоря уже о том, где происходит неверный состав и как его исправить, или почему проблема с актером появляется только тогда, когда в документе XML есть комментарии (Readchildrenof - это единственный метод во всем моей базе кода, в котором подразумевает xmlnodes. Отдельный состав между различными типами XMLNODE - но я проверяю (дважды), чтобы убедиться, что узел имеет правильный тип, прежде чем я выполняю актер.

Подробнее здесь: https://stackoverflow.com/questions/797 ... at-contain
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»