Simple question~
I have a node in an XML node which is set up using this format in a file: <Vector3 x=“0” y=“0” z="0/>
And I’d like to know how to change that into an actual vector3. I’ve never done XML parsing or anything before so I have no idea how this will work.
You’d actually parse them as three separate float values and then create the Vector3 from those, using zeros if/where the parsed values were null (for safety). As for how exactly you’d get the data from the file, it depends on how it’s set up and the method you’re using. I’m going to assume an XMLDocument methodology for the purposes of explanation.
Given the format of the element, I’d say "parent.GetElementsByTagName(“Vector3”) would return a list of XMLElements under the “parent” XMLElement, whatever that is, which you’d then iterate through and:
float xVector = Float.Parse(iteratedElement.GetAttribute("x", iteratedElement.NamespaceURI));
float yVector = Float.Parse(iteratedElement.GetAttribute("y", iteratedElement.NamespaceURI));
float zVector = Float.Parse(iteratedElement.GetAttribute("z", iteratedElement.NamespaceURI));
Vector3 parsedVector = new Vector3(xVector, yVector, zVector);
of, safer:
float? xVector = float.TryParse(iteratedElement.GetAttribute("x", iteratedElement.NamespaceURI).Trim());
float? yVector = float.TryParse(iteratedElement.GetAttribute("y", iteratedElement.NamespaceURI).Trim());
float? zVector = float.TryParse(iteratedElement.GetAttribute("z", iteratedElement.NamespaceURI).Trim());
Vector3 parsedVector = new Vector3(xVector.GetValueOrDefault(), yVector.GetValueOrDefault(), zVector.GetValueOrDefault());
or, much the same as above but without the nullable floats and such:
string[] vectorString = new string[3];
vectorString[0] = iteratedElement.GetAttribute("x", iteratedElement.NamespaceURI);
vectorString[1] = iteratedElement.GetAttribute("y", iteratedElement.NamespaceURI);
vectorString[2] = iteratedElement.GetAttribute("z", iteratedElement.NamespaceURI);
float vectorFloat[] = new float[3];
for(int i = 0; i < vectorString.Length; i++)
{
if(vectorString[i] == null || vectorString[i].Trim() == "" || !float.TryParse(vectorString[i].Trim(), out vectorFloat[i]))
vectorFloat[i] = 0f;
}
Vector3 safeVector3 = new Vector3(vectorFloat[0], vectorFloat[1], vectorFloat[2]);