Xml C#根据另一个节点查找节点值

时间:2015-07-14 17:05:16

标签: c# xml xml-parsing

如果SubtypeName的文本等于“Weight”

,我需要帮助查找Position的属性

问题是,xml文件中会有多个MyObjectBuilder_EntityBase元素(如下所示)可能满足或不满足这些要求,但具有相同的结构。

属性x y和z将存储在满足条件的每个列表变量的三个相应列表变量中。

<MyObjectBuilder_EntityBase xsi:type="MyObjectBuilder_CubeGrid">
  <EntityId>173933426524952854</EntityId>
  <PersistentFlags>CastShadows InScene</PersistentFlags>
  <PositionAndOrientation>
    <Position x="32.206989288330078" y="28.401615142822266" z="11.562240600585937" />
    <Forward x="0.323335081" y="-0.00425125659" z="-0.946275" />
    <Up x="-0.9462663" y="-0.007667198" z="-0.32329765" />
  </PositionAndOrientation>
  <GridSizeEnum>Small</GridSizeEnum>
  <CubeBlocks>
    <MyObjectBuilder_CubeBlock xsi:type="MyObjectBuilder_CubeBlock">
      <SubtypeName>Weight</SubtypeName>
      <EntityId>173933426524952855</EntityId>
      <Min x="0" y="0" z="0" />
      <BlockOrientation Forward="Forward" Up="Up" />
      <ColorMaskHSV x="0" y="-1" z="0" />
      <ShareMode>None</ShareMode>
      <DeformationRatio>0</DeformationRatio>
    </MyObjectBuilder_CubeBlock>
  </CubeBlocks>
  <IsStatic>false</IsStatic>
  <Skeleton />
  <LinearVelocity x="0" y="0" z="0" />
  <AngularVelocity x="0" y="0" z="0" />
  <XMirroxPlane xsi:nil="true" />
  <YMirroxPlane xsi:nil="true" />
  <ZMirroxPlane xsi:nil="true" />
  <BlockGroups />
  <Handbrake>false</Handbrake>
  <DisplayName>Grid 2854</DisplayName>
  <DestructibleBlocks>true</DestructibleBlocks>
  <CreatePhysics>true</CreatePhysics>
  <EnableSmallToLargeConnections>true</EnableSmallToLargeConnections>
</MyObjectBuilder_EntityBase>

我必须开始的代码是:

private void button3_Click(object sender, EventArgs e)
    {
        String choice;
        switch (comboBox1.SelectedIndex)
        {
            case 0: //player
                choice = "Player";
                break;

            case 1://weight
                choice = "Weight";
                break;

            case 2://catapult
                choice = "CatapultHead";
                break;

            case 3://ropething
                choice = "RopeEndingSmall";
                break;

            case 4://ropethingbig
                choice = "RopeReleaseSmall";
                break;

            case 5://turncross
                choice = "TurnCrossSmall";
                break;

            default:
                choice = "Blah";
                break;

        }


        Random rand = new Random();

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(pathtree);

        XmlReader xmlReader = XmlReader.Create(pathtree);
        XmlNamespaceManager nsmanager = new XmlNamespaceManager(xmlDoc.NameTable);
        nsmanager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

        List<double> x = new List<double>();
        List<double> y = new List<double>();
        List<double> z = new List<double>();
        ////MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_CubeGrid']/CubeBlocks/MyObjectBuilder_CubeBlock[@xsi:type = 'MyObjectBuilder_CubeBlock']/SubtypeName
        //xmlReader.
        while (xmlReader.Read())
        {
            switch (comboBox1.SelectedIndex)
            {
                case 0: //player
                    x.Add( Convert.ToDouble(xmlDoc.SelectSingleNode("//MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_Character']/PositionAndOrientation/Position", nsmanager).Attributes["x"].Value) );
                    y.Add( Convert.ToDouble(xmlDoc.SelectSingleNode("//MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_Character']/PositionAndOrientation/Position", nsmanager).Attributes["y"].Value) );
                    z.Add( Convert.ToDouble(xmlDoc.SelectSingleNode("//MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_Character']/PositionAndOrientation/Position", nsmanager).Attributes["z"].Value) );
                    break;

                case 1://weight
                    //xmlDoc.SelectNodes()
                    //x.add(from type in xmlDoc.SelectSingleNode("//MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_Character']/PositionAndOrientation/Position", nsmanager));
                    //Select x.value('Description[1]','varchar(max)') as 'description' FROM xmlDoc.SelectNodes('//IncomeItem[TypeId=29]') i(x)
                    break;

                case 2://catapult
                    break;

                case 3://ropething
                    break;

                case 4://ropethingbig
                    break;

                case 5://turncross
                    break;

                default:
                    break;

            }

如果子类型等于“播放器”,我可以轻松检索它,因为只有一个。剩下的很难,因为不止一个。

当我遇到它时,如果符合条件,我还需要删除MyObjectBuilder元素。

2 个答案:

答案 0 :(得分:0)

必须剥离命名空间才能加载它,但这应该可行,无论如何都可以在本地工作

 var xml = "<MyObjectBuilder_EntityBase>" +
        "<EntityId>173933426524952854</EntityId>" +
        "<PersistentFlags>CastShadows InScene</PersistentFlags>" +
        "<PositionAndOrientation>" +
        "<Position x=\"32.206989288330078\" y=\"28.401615142822266\" z=\"11.562240600585937\" />" +
        "<Forward x=\"0.323335081\" y=\"-0.00425125659\" z=\"-0.946275\" />" +
        "<Up x=\"-0.9462663\" y=\"-0.007667198\" z=\"-0.32329765\" />" +
        "</PositionAndOrientation>" +
        "<GridSizeEnum>Small</GridSizeEnum>" +
        "<CubeBlocks>" +
        "<MyObjectBuilder_CubeBlock>" +
        "<SubtypeName>Weight</SubtypeName>" +
        "<EntityId>173933426524952855</EntityId>" +
        "<Min x=\"0\" y=\"0\" z=\"0\" />" +
        "<BlockOrientation Forward=\"Forward\" Up=\"Up\" />" +
        "<ColorMaskHSV x=\"0\" y=\"-1\" z=\"0\" />" +
        "<ShareMode>None</ShareMode>" +
        "<DeformationRatio>0</DeformationRatio>" +
        "</MyObjectBuilder_CubeBlock>" +
        "</CubeBlocks>" +
        "<IsStatic>false</IsStatic>" +
        "<Skeleton />" +
        "<LinearVelocity x=\"0\" y=\"0\" z=\"0\" />" +
        "<AngularVelocity x=\"0\" y=\"0\" z=\"0\" />" +
        "<XMirroxPlane />" +
        "<YMirroxPlane />" +
        "<ZMirroxPlane />" +
        "<BlockGroups />" +
        "<Handbrake>false</Handbrake>" +
        "<DisplayName>Grid 2854</DisplayName>" +
        "<DestructibleBlocks>true</DestructibleBlocks>" +
        "<CreatePhysics>true</CreatePhysics>" +
        "<EnableSmallToLargeConnections>true</EnableSmallToLargeConnections>" +
        "</MyObjectBuilder_EntityBase>";

        var doc = new XmlDocument();
        doc.LoadXml(xml);

        var xlist = new List<string>();
        var ylist = new List<string>();
        var zlist = new List<string>();

        var subtypeName = doc.SelectSingleNode("//SubtypeName");
        if (subtypeName.InnerText == "Weight")
        {
            var position = doc.SelectSingleNode("//Position");
            xlist.Add(position.Attributes["x"].Value);
            ylist.Add(position.Attributes["y"].Value);
            zlist.Add(position.Attributes["z"].Value);

        }

答案 1 :(得分:0)

用一点肘部回答我自己的问题:

private void button3_Click(object sender, EventArgs e)
    {
        String choice;
        switch (comboBox1.SelectedIndex)
        {
            case 0: //player
                choice = "Player";
                break;

            case 1://weight
                choice = "Weight";
                break;

            case 2://catapult
                choice = "CatapultHead";
                break;

            case 3://ropething
                choice = "RopeEndingSmall";
                break;

            case 4://ropethingbig
                choice = "RopeReleaseSmall";
                break;

            case 5://turncross
                choice = "TurnCrossSmall";
                break;

            default:
                choice = "Blah";
                break;

        }


        Random rand = new Random();

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load(pathtree);

        //XmlReader xmlReader = XmlReader.Create(pathtree);
        XmlNamespaceManager nsmanager = new XmlNamespaceManager(xmlDoc.NameTable);
        nsmanager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

        List<double> x = new List<double>();
        List<double> y = new List<double>();
        List<double> z = new List<double>();
        ////MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_CubeGrid']/CubeBlocks/MyObjectBuilder_CubeBlock[@xsi:type = 'MyObjectBuilder_CubeBlock']/SubtypeName
        //xmlReader.
        while (true)
        {
            switch (comboBox1.SelectedIndex)
            {
                case 0: //player
                    x.Add( Convert.ToDouble(xmlDoc.SelectSingleNode("//MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_Character']/PositionAndOrientation/Position", nsmanager).Attributes["x"].Value) );
                    y.Add( Convert.ToDouble(xmlDoc.SelectSingleNode("//MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_Character']/PositionAndOrientation/Position", nsmanager).Attributes["y"].Value) );
                    z.Add( Convert.ToDouble(xmlDoc.SelectSingleNode("//MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_Character']/PositionAndOrientation/Position", nsmanager).Attributes["z"].Value) );
                    break;

                case 1:
                    XmlNodeList nodeCollection = xmlDoc.SelectNodes("//MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_CubeGrid']",nsmanager);
                    if (nodeCollection != null) { 
                    textBox2.Text += nodeCollection.Count;
                    }
                    for (int j = 0; j < nodeCollection.Count; j++)
                    {
                        ///////
                        if (nodeCollection[j].SelectSingleNode("//CubeBlocks/MyObjectBuilder_CubeBlock[@xsi:type = 'MyObjectBuilder_CubeBlock']/SubtypeName",nsmanager).InnerText.Equals("Weight"))
                        {
                            var position = nodeCollection[j].SelectSingleNode("//PositionAndOrientation/Position");

                            x.Add(Convert.ToDouble(position.Attributes["x"].Value));
                            y.Add(Convert.ToDouble(position.Attributes["y"].Value));
                            z.Add(Convert.ToDouble(position.Attributes["z"].Value));

                        }
                    }
                    //xmlReader.ReadToFollowing()
                    //xmlDoc.SelectNodes()
                    //x.add(from type in xmlDoc.SelectSingleNode("//MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_Character']/PositionAndOrientation/Position", nsmanager));
                    //Select x.value('Description[1]','varchar(max)') as 'description' FROM xmlDoc.SelectNodes('//IncomeItem[TypeId=29]') i(x)
                    break;

                case 2://catapult
                    break;

                case 3://ropething
                    break;

                case 4://ropethingbig
                    break;

                case 5://turncross
                    break;

                default:
                    break;
            }
            break;
            /*
            x.Add( Convert.ToDouble(xmlDoc.SelectSingleNode("//MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_Character']/PositionAndOrientation/Position", nsmanager).Attributes["x"].Value) );
            y.Add( Convert.ToDouble(xmlDoc.SelectSingleNode("//MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_Character']/PositionAndOrientation/Position", nsmanager).Attributes["y"].Value) );
            z.Add( Convert.ToDouble(xmlDoc.SelectSingleNode("//MyObjectBuilder_Sector/SectorObjects/MyObjectBuilder_EntityBase[@xsi:type = 'MyObjectBuilder_Character']/PositionAndOrientation/Position", nsmanager).Attributes["z"].Value) );
            */
        }
        for (int i = 0; i < (x.Count); i++)
        {
            createTree(x[i], y[i], z[i]);
            textBox2.Text += "\r\nCREATED A TREE\r\n";
        }
    }