Created
September 12, 2024 09:48
-
-
Save CN-CODEGOD/0106b8007928cde15985e4d12687c6a6 to your computer and use it in GitHub Desktop.
如何逆推多层级的结构代码
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 解释: | |
| 在代码中可能遇见一种情况需要向外一层层的解剖一个object,但是我们只能从根据内部推出外部. | |
| 实例: | |
| 我们需要通过一个xml表构建一个psobject | |
| 此时我们要构建这个psobject,我们试从xml一层层地剖析 | |
| ``` | |
| ([pscustomobject]@{roadcoordinate=@{ | |
| > roadcoordinte1=@{x=1 | |
| > y=1 | |
| > z=1 | |
| > } | |
| > roadcoordinate2=@{ | |
| > x=1 | |
| > y=1 | |
| > z=1} | |
| > } | |
| > dimension= "nether" | |
| > } | |
| > ) | |
| ``` | |
| 发现如果要构建这个psobject,我们需要循环,循环到内部再没有object为止 | |
| 所以我们简单定义一个xml表能表达这个psobject | |
| ``` | |
| <object type="road"> | |
| <property name="roadcoordinate"> | |
| <property name="roadcoordinate1"> | |
| <property name="x">0</property> | |
| <property name="y">0</property> | |
| <property name="z">0</property> | |
| </property> | |
| <property name="roadcoordinate2"> | |
| <property name="x">0</property> | |
| <property name="y">0</property> | |
| <property name="z">0</property> | |
| </property> | |
| </property> | |
| <property name="name" /> | |
| <property name="dimension">nether</property> | |
| <property name="id">0</property> | |
| </object> | |
| ``` | |
| 此时我们要根据xml表逆推这个psobject | |
| 我们注意到如果从外面推,我们一开始并不知道有多少层,也不知道内部的数据是什么,不知道要经过多少次循环 | |
| 这时我们可以使用foreach 尝试循环.如果发现内部有object就执行内部循环,直到没有object为止,从内部慢慢地推出这个object | |
| 实例代码 | |
| 内循环: | |
| function rehydrate([System.Xml.XmlElement]$object){ | |
| if (($object -ne $null) -and ($null -ne $object.property )){ | |
| $psobject =new-object pscustomobject | |
| foreach ($property in $object.property){ | |
| if ($property.property.name -like 'property'){ | |
| $psobject |add-Member noteproperty $property.name ($property.property| % {rehydrate $_}) | |
| } | |
| } | |
| } | |
| } | |
| 这段简单的代码即可从内部获取所有内部的child |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment